Interfaces in C++

Interfaces are a powerful feature in object-oriented programming that define a contract for classes to implement.

#include <iostream>
#include <cmath>
#include <memory>

// Here's a basic interface for geometric shapes.
class Geometry {
public:
    virtual double area() const = 0;
    virtual double perim() const = 0;
    virtual ~Geometry() = default;
};

// For our example we'll implement this interface on
// `Rect` and `Circle` classes.
class Rect : public Geometry {
public:
    Rect(double w, double h) : width(w), height(h) {}
    
    double area() const override {
        return width * height;
    }
    
    double perim() const override {
        return 2*width + 2*height;
    }
    
private:
    double width, height;
};

class Circle : public Geometry {
public:
    Circle(double r) : radius(r) {}
    
    double area() const override {
        return M_PI * radius * radius;
    }
    
    double perim() const override {
        return 2 * M_PI * radius;
    }
    
private:
    double radius;
};

// If a function takes a pointer or reference to the interface type,
// we can pass any object that implements that interface.
// Here's a generic `measure` function taking advantage of this
// to work on any `Geometry`.
void measure(const Geometry& g) {
    std::cout << "Area: " << g.area() << std::endl;
    std::cout << "Perimeter: " << g.perim() << std::endl;
}

int main() {
    Rect r(3, 4);
    Circle c(5);

    // The `Circle` and `Rect` classes both
    // implement the `Geometry` interface so we can use
    // instances of these classes as arguments to `measure`.
    measure(r);
    measure(c);

    return 0;
}

To run the program, compile it and then execute:

$ g++ -std=c++14 interfaces.cpp -o interfaces
$ ./interfaces
Area: 12
Perimeter: 14
Area: 78.5398
Perimeter: 31.4159

In C++, interfaces are typically implemented using abstract base classes with pure virtual functions. The Geometry class serves as our interface, defining the contract that all geometric shapes must fulfill.

The Rect and Circle classes inherit from Geometry and provide concrete implementations of the area() and perim() methods.

The measure function demonstrates polymorphism: it can work with any object that implements the Geometry interface, allowing for flexible and extensible code.

Note that C++ doesn’t have a built-in interface keyword like some other languages. Instead, we use abstract classes to achieve similar functionality. Also, C++ uses virtual for method overriding and requires override keyword for clarity in derived classes.

To learn more about C++ interfaces and abstract classes, check out this cppreference page.