Sobes.tech
Junior — Middle

Does C++ have a concept of interface similar to that in other programming languages?

sobes.tech AI

Answer from AI

In C++, there is no separate keyword 'interface' like in Java or C#. However, the interface equivalent is achieved through abstract classes that contain only pure virtual functions.

Example of an interface in C++:

class IShape {
public:
    virtual double area() const = 0;  // pure virtual function
    virtual ~IShape() {}               // virtual destructor
};

class Circle : public IShape {
    double radius;
public:
    Circle(double r) : radius(r) {}
    double area() const override {
        return 3.14159 * radius * radius;
    }
};

Such an abstract class cannot be instantiated directly and defines a contract that inheriting classes must implement. This is the equivalent of an interface.