Interfaces in C++


A pure interface in C++ refers to an interface class that contains only pure virtual functions and no implementation. An interface class defines the contracts for a set of related classes, but it does not provide any implementation. Classes that derive from the interface class must provide the implementation for the pure virtual functions.

 

Here's an example of how to create a pure interface in C++:

#include <iostream>

// Declare the pure interface class
class Shape {
 public:
  // Pure virtual function
  virtual void draw() = 0;
};

// Derived class that implements the pure virtual function
class Circle : public Shape {
 public:
  void draw() { std::cout << "Drawing a Circle" << std::endl; }
};

// Derived class that implements the pure virtual function
class Square : public Shape {
 public:
  void draw() { std::cout << "Drawing a Square" << std::endl; }
};

int main() {
  Circle circle;
  Square square;

  Shape *shapes[] = {&circle, &square};

  for (auto shape : shapes) {
    shape->draw();
  }

  return 0;
}

In this example, the Shape class is the pure interface class, and the Circle and Square classes are derived classes that implement the draw function. The main function demonstrates how you can use polymorphism to draw a circle and a square, without having to know the specific type of shape being drawn.

 

Summary

This article provides a simple example of how to use pure interfaces in C++. A pure interface class defines the contracts for a set of related classes, but it does not provide any implementation. The article demonstrates how to create a pure interface class, and how to use polymorphism to draw different shapes without having to know the specific type of shape being drawn.

'C++' 카테고리의 다른 글

Working with Shared Pointers in C++  (0) 2023.02.10
Understanding Callback Functions in C++  (0) 2023.02.10
Compiling C++ Code on a Mac using the Terminal and GCC  (0) 2023.02.10
Key Features of C++14  (0) 2023.02.10
Lambda Functions in C++  (0) 2023.02.10

+ Recent posts