Polymorphism in C++
Polymorphism means “many forms.” In simple terms, it refers to the ability of something to take on different forms or behaviors in different situations.
A real-life example of polymorphism is a person who can play different roles at the same time. For instance, a man can be a father, a husband, and an employee all at once. This is an example of polymorphism.
Polymorphism is an important concept in Object-Oriented Programming (OOP). In C++, there are two main types of polymorphism:
1. Compile-time Polymorphism (Static Polymorphism / Early Binding):
- This happens when functions or operators are overloaded.
- Function overloading means defining multiple functions with the same name but different parameters (either a different number of arguments or different types of arguments).
- Operator overloading means giving a new meaning to an operator (like
+
,-
, etc.) for user-defined types (classes).
Compile-time polymorphism is determined at compile time, which is why it’s called static polymorphism or early binding.
Example (Function Overloading) in C++
#include <iostream> using namespace std; class Printer { void print(double d) { int main() { |
Output:
Printing integer: 5
Printing double: 3.14
2. Runtime Polymorphism (Dynamic Polymorphism / Late Binding)
- Runtime Polymorphism is enabled by virtual functions and function-overriding
- Function overriding occurs when a function is overridden in a derived class. In this case, the function in the base class is redefined in the derived class with the same signature.
- The decision about which function to call is made at runtime, which is why it’s called dynamic polymorphism or late binding.
Important: Virtual functions and function overriding are related, they are not the same concept. |
Example (Function Overriding) in C++
#include <iostream> using namespace std; // Base class // Derived class int main() { // Call speak() method on both objects return 0; |
Output
Animal speaks
Dog barks
Explanation
- Base class
Animal
: It has aspeak()
function, which prints “Animal speaks.” - Derived class
Dog
: It overrides thespeak()
function to print “Dog barks” instead. - Function Overriding: In C++, when a function in the derived class has the same name and signature as a function in the base class, it overrides the base class function.