Lesson 5 of 8Article17 min
Inheritance and Polymorphism
Polymorphism lets derived classes provide specialized behavior through virtual methods. Base pointers can call overridden methods at runtime.
Runtime polymorphism
Polymorphism lets derived classes provide specialized behavior through virtual methods. Base pointers can call overridden methods at runtime.
Virtual method dispatch
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() const { return 0; }
virtual ~Shape() = default;
};
class Rectangle : public Shape {
double w, h;
public:
Rectangle(double w, double h) : w(w), h(h) {}
double area() const override { return w * h; }
};Design guidelines
- Use virtual destructors in polymorphic base classes.
- Favor composition when inheritance hierarchy grows too complex.
- Override methods with clear contracts and const-correctness.