"Many forms" — the ability of different objects/classes to respond to the same interface/message in type-specific ways.
| Type | Mechanism | Resolved | Example |
|---|---|---|---|
| Compile-time (static) | Function overloading, Operator overloading | At compile time — compiler picks the matching version by signature | add(int,int) vs add(float,float) |
| Runtime (dynamic) | Virtual functions + inheritance | At runtime — via the vtable, based on the object's actual type | Shape* s = new Circle(); s->area(); calls Circle::area() |
This distinction matters for exams: many students only associate polymorphism with virtual functions, but function/operator overloading is polymorphism too, just resolved earlier (at compile time instead of runtime).
Polymorphism means the same interface (function name/operator) behaves differently depending on context. C++ achieves this two distinct ways:
class MathUtil
{
public:
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; } // same name, different signature
};
// The COMPILER decides which add() to call based on argument types, before the program even runs
class Shape { public: virtual void draw() { cout << "shape\n"; } };
class Circle : public Shape { public: void draw() override { cout << "circle\n"; } };
Shape* s = new Circle();
s->draw(); // prints "circle" -- decided at RUNTIME, based on the actual object type
A question like "what is polymorphism, give an example" is often answered with ONLY the virtual-function case — missing half the marks available for also covering function/operator overloading. Both are legitimate forms of polymorphism; they just resolve at different times.
| Scenario | Type |
|---|---|
| Two functions, same name, different parameter lists | Compile-time |
A base class pointer calling an overridden virtual method |
Runtime |
a + b calling a custom operator+ |
Compile-time |
An array of Shape* calling draw() and each shape drawing differently |
Runtime |
Shape* s = new Circle(); s->draw(); calling Circle::draw() is resolved:
virtual?