OOP and Polymorphism

OOP and Polymorphism

Use inheritance and virtual dispatch carefully, and learn when composition is better.

OOP and Polymorphism

Base class design

class Shape {
public:
    virtual ~Shape() = default;
    virtual double area() const = 0;
};

Derived type

class Rectangle : public Shape {
public:
    Rectangle(double w, double h) : width_{w}, height_{h} {}
    double area() const override { return width_ * height_; }

private:
    double width_{};
    double height_{};
};

Main lessons

When std::variant is simpler

If the set of alternatives is fixed, a sum type can be simpler than an inheritance tree:

using Shape = std::variant<Circle, Rectangle, Triangle>;

This avoids heap allocation and virtual dispatch in many designs.

Interface design rules