Sobes.tech
Middle

What is an interface class in C++?

sobes.tech AI

Answer from AI

An interface class in C++ is a class that defines a set of functions (interface) that must be implemented by derived classes. It cannot be instantiated directly, as it contains pure virtual functions and possibly data members.

Key features:

  • Contains pure virtual functions: A function declared as pure virtual using = 0; after its declaration. Derived classes must override all pure virtual functions to become concrete classes (which can be instantiated).
  • Abstract class: An interface class is a special case of an abstract class.
  • No implementation of methods: Usually, an interface class does not contain implementations for virtual functions. In rare cases, there may be implementations for non-virtual functions or virtual functions (if some common functionality is needed, but then it is no longer a "pure" interface).
  • Used for polymorphism: Allows working with objects of different derived classes through a pointer or reference to the base interface class.
  • Contract building: Defines "what the class should do" without specifying "how".

Example:

// Interface class
class IDrawable {
public:
    // Pure virtual function
    virtual void draw() const = 0;

    // Virtual destructor is important for proper deletion
    // of derived class objects through a pointer to the base
    virtual ~IDrawable() = default;
};

// Derived class implementing the interface
class Circle : public IDrawable {
public:
    void draw() const override {
        // Implementation of circle drawing
        // ...
    }
};

// Derived class implementing the interface
class Square : public IDrawable {
public:
    void draw() const override {
        // Implementation of square drawing
        // ...
    }
};

void render(const IDrawable& obj) {
    obj.draw(); // Polymorphic call
}