Polymorphism means one name, many forms.
| Compile-time (static) | Run-time (dynamic) |
|---|---|
| Function overloading, operator overloading | Function overriding with virtual functions |
| Decided by the compiler | Decided while running (via vtable) |
| Faster | More flexible |
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
-
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++).
-
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.