Skip to content

Polymorphism

Polymorphism means one interface, many forms. The same function/operator behaves differently based on the context.

Think of it like a person — same person behaves differently as a son, employee, and friend.

Two Types

Polymorphism
 ├── Compile-time (Static) → resolved at compile time
 │     ├── Function Overloading
 │     └── Operator Overloading

 └── Runtime (Dynamic) → resolved at runtime
       └── Function Overriding (Virtual Functions)

1. Function Overloading

cpp
class Calculator {
public:
    int add(int a, int b) { return a + b; }
    double add(double a, double b) { return a + b; } // same name, different params
    int add(int a, int b, int c) { return a + b + c; }
};

2. Operator Overloading

cpp
class Complex {
public:
    int real, imag;
    Complex operator+(Complex& c) {
        Complex temp;
        temp.real = real + c.real;
        temp.imag = imag + c.imag;
        return temp;
    }
};

3. Runtime Polymorphism (Virtual Functions)

cpp
class Animal {
public:
    virtual void sound() { cout << "Some sound" << endl; }
};

class Dog : public Animal {
public:
    void sound() override { cout << "Dog barks" << endl; }
};

class Cat : public Animal {
public:
    void sound() override { cout << "Cat meows" << endl; }
};

int main() {
    Animal* a;
    Dog d; Cat c;
    a = &d; a->sound(); // Dog barks — decided at RUNTIME
    a = &c; a->sound(); // Cat meows — decided at RUNTIME
}

Without virtual, it would always call Animal::sound(). The virtual keyword enables dynamic dispatch.

Compile-time vs Runtime

Compile-timeRuntime
Also calledStatic polymorphismDynamic polymorphism
Resolved atCompile timeRuntime
Achieved byOverloadingOverriding + virtual
SpeedFasterSlightly slower (VTable lookup)
FlexibilityLess flexibleMore flexible

Overloading vs Overriding

OverloadingOverriding
WhereSame classParent & Child class
SignatureDifferentSame
KeywordNonevirtual + override
TypeCompile-timeRuntime

One-liner: "Polymorphism allows the same interface to behave differently depending on the object, achieved via overloading at compile time and virtual functions at runtime."