39

Polymorphism means one name, many forms.

Compile-time (static)Run-time (dynamic)
Function overloading, operator overloadingFunction overriding with virtual functions
Decided by the compilerDecided while running (via vtable)
FasterMore flexible
Run-time polymorphism C++ 24 lines
class Shape {
public:
    virtual double area() { return 0; }     // virtual = can be overridden
    virtual ~Shape() {}
};

class Circle : public Shape {
    double r;
public:
    Circle(double r) : r(r) {}
    double area() override { return 3.1416 * r * r; }
};

class Square : public Shape {
    double a;
public:
    Square(double a) : a(a) {}
    double area() override { return a * a; }
};

Shape *s1 = new Circle(2);
Shape *s2 = new Square(3);
cout << s1->area();   // 12.56  → Circle's area()
cout << s2->area();   // 9      → Square's area()

Q & A

  1. Overloading vs overriding?
    Overloading: same name, different parameters, in the same class, compile time. Overriding: same signature in parent and child, run time, needs inheritance (and virtual in C++).
  2. Why should a base class destructor be virtual?
    So that deleting a child object through a base pointer also runs the child destructor; otherwise resources leak.