OOP and Polymorphism
OOP and Polymorphism
Use inheritance and virtual dispatch carefully, and learn when composition is better.
OOP and Polymorphism
Use inheritance and virtual dispatch carefully, and learn when composition is better.
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0;
};
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_{};
};
std::variant is simplerIf 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.