C++ Polymorphism
Polymorphism is a core concept of object-oriented programming in C++ that allows objects of different classes to be treated as objects of a common base class. It means “many forms” and enables the same function or operator to behave differently based on the context.
Types of Polymorphism
- Function overloading and operator overloading implement compile-time polymorphism.
- Virtual functions implement run-time polymorphism, enabling dynamic behavior based on object type.
- Polymorphism improves code flexibility and reusability in object-oriented programming.
Next Topic
Next, learn about Function Overriding in C++.
- Compile-time (or Static) Polymorphism: Achieved using function overloading and operator overloading.
- Run-time (or Dynamic) Polymorphism: Achieved using virtual functions and inheritance.
Example: Compile-time Polymorphism (Function Overloading)
#include <iostream>
using namespace std;
class Math {
public:
// Function to add two integers
int add(int a, int b) {
return a + b;
}
// Function to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
};
int main() {
Math m;
cout << "Sum of 2 and 3: " << m.add(2, 3) << endl;
cout << "Sum of 2, 3, 4: " << m.add(2, 3, 4) << endl;
return 0;
}
Output
Sum of 2 and 3: 5 Sum of 2, 3, 4: 9
Example: Run-time Polymorphism (Virtual Function)
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() { // Virtual function
cout << "Some generic sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() override {
cout << "Woof Woof" << endl;
}
};
class Cat : public Animal {
public:
void sound() override {
cout << "Meow" << endl;
}
};
int main() {
Animal *a1;
Dog d;
Cat c;
a1 = &d;
a1->sound(); // Calls Dog's sound()
a1 = &c;
a1->sound(); // Calls Cat's sound()
return 0;
}
Output
Woof Woof Meow
Important Notes
- Function overloading and operator overloading implement compile-time polymorphism.
- Virtual functions implement run-time polymorphism, enabling dynamic behavior based on object type.
- Polymorphism improves code flexibility and reusability in object-oriented programming.
Next Topic
Next, learn about Function Overriding in C++.