Polymorphism is a core concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. It enables a single interface to represent different underlying forms (data types). There are two main types of polymorphism:

Compile-time Polymorphism (Static Binding)

  • Achieved through method overloading or operator overloading.
  • The method to be invoked is determined at compile time.
#include <iostream>
 
class Printer {
public:
    void print(int value) {
        printf("Printing int: %d\n", value);
    }
 
    void print(double value) {
        printf("Printing double: %.2f\n", value);
    }
 
    void print(const char* value) {
        printf("Printing string: %s\n", value);
    }
};
 
int main() {
    Printer printer;
    printer.print(42);
    printer.print(3.14);
    printer.print("Hello");
    return 0;
}
Output
Printing int: 42
Printing double: 3.14
Printing string: Hello

Runtime Polymorphism (Dynamic Binding)

  • Achieved through method overriding.
  • The method to be invoked is determined at runtime based on the object’s actual type.
#include <iostream>
 
using namespace std;
 
class Animal {
public:
    virtual void makeSound() = 0;
};
 
class Dog : public Animal {
public:
    void makeSound() {
        printf("Bark\n");
    }
};
 
class Cat : public Animal {
public:
    void makeSound(){
        printf("Meow\n");
    }
};
 
int main() {
    Animal* animals[] = {
        new Dog(),
        new Cat()
    };
 
    for (Animal* animal : animals) {
        animal->makeSound();
    }
 
    for (Animal* animal : animals) {
        delete animal;
    }
    return 0;
}
Output
Bark
Meow