Polymorphism is an important feature of object-oriented programming. Polymorphism refers to “one name” “multiple forms”. Polymorphism means a program contains the same function name performs different functionality.
Polymorphism is classified into two types. These are:
- Compile time polymorphism
- Run time polymorphism
Compile time polymorphism: It is achieved by function overloading or operator overloading. This is also known as early binding or static binding.
Run time polymorphism: It is achieved by function overriding. This is also known as late binding or dynamic binding.
Simple example of polymorphism
A class ‘Polymorphism’ contains two functions with same name func.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include<iostream> using namespace std; class Polymorphism { public: // function with 1 int parameter void func(int x) { cout << "value of x is " << x << endl; } // function with same name and 2 int parameters void func(int x, int y) { cout << "value of x and y is " << x << ", " << y << endl; } }; int main() { Polymorphism obj1; obj1.func(5); obj1.func(10,20); return 0; } |
Output:
1 2 3 4 |
value of x is 5 value of x and y is 10, 20 |