Polymorphism in C++
1. What is Polymorphism?
Polymorphism means "many forms". In C++, it allows one function or object to behave differently in
different situations.
Types of Polymorphism:
1. Compile-time Polymorphism (Static Polymorphism)
2. Decided at compile time.
3. Achieved using function overloading or operator overloading.
4. Run-time Polymorphism (Dynamic Polymorphism)
5. Decided at run time.
6. Achieved using function overriding with inheritance and virtual functions.
2. Compile-time Polymorphism (Function Overloading)
#include <iostream>
using namespace std;
class Math {
public:
void add(int a, int b) {
cout << "Sum of integers: " << a + b << endl;
}
void add(double a, double b) {
cout << "Sum of doubles: " << a + b << endl;
}
void add(int a, int b, int c) {
cout << "Sum of three integers: " << a + b + c << endl;
}
};
int main() {
Math obj;
obj.add(5, 10);
obj.add(2.5, 3.7);
obj.add(1, 2, 3);
return 0;
}
Output:
1
Sum of integers: 15
Sum of doubles: 6.2
Sum of three integers: 6
Explanation: - Same function name add() is used for different types/number of parameters. -
Compiler decides which function to call at compile time.
Diagram:
obj.add(5,10) -> add(int,int)
obj.add(2.5,3.7) -> add(double,double)
obj.add(1,2,3) -> add(int,int,int)
(Color code each arrow in different colors for clarity)
3. Run-time Polymorphism (Virtual Function)
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() {
cout << "Animal makes a 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* a1;
Dog d;
Cat c;
2
a1 = &d;
a1->sound(); // Calls Dog's sound
a1 = &c;
a1->sound(); // Calls Cat's sound
return 0;
}
Output:
Dog barks
Cat meows
Explanation: - virtual keyword enables overriding. - Base class pointer calls derived class function
at runtime. - Achieved using vtable and vptr internally.
Diagram:
Animal* a1
|
+--> Dog object -> calls Dog::sound()
|
+--> Cat object -> calls Cat::sound()
(Use different colors for Dog and Cat arrows)
4. Summary Table
Type Decided Achieved By Example
Compile- Compile Function/Operator add(int,int) and
time time overloading add(double,double)
Virtual functions
Run-time Run time Animal -> Dog/Cat
(Inheritance)
Note: Polymorphism allows flexible, reusable, and maintainable code. Using colourful highlights
and diagrams helps make revision easier.