Polymorphism in C++
Real Life Example of Polymorphism in C++
The process of representing one Form in multiple forms is known as Polymorphism. Here one form represent original form or original method always resides in base class and multiple forms represents overridden method which resides in derived classes.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and morphs means forms. So polymorphism means many forms.
Real life example of Polymorphism in C++
Suppose if you are in class room that time you behave like a student, when you are in market at that time you behave like a customer, when you at your home at that time you behave like a son or daughter, Here one person have different-different behaviors.
Type of polymorphism
- Compile time polymorphism
- Run time polymorphism
Compile time polymorphism
In C++ programming you can achieve compile time polymorphism in two way, which is given below;
- Method overloading
- Method overriding
Method Overloading in C++
Whenever same method name is exiting multiple times in the same class with different number of parameter or different order of parameters or different types of parameters is known as method overloading. In below example method "sum()" is present in Addition class with same name but with different signature or arguments.
Example of Method Overloading in C++
#include<iostream.h> #include<conio.h> class Addition { public: void sum(int a, int b) { cout<<a+b; } void sum(int a, int b, int c) { cout<<a+b+c; } }; void main() { clrscr(); Addition obj; obj.sum(10, 20); cout<<endl; obj.sum(10, 20, 30); }
Output
30 60
Method Overriding in C++
Define any method in both base class and derived class with same name, same parameters or signature, this concept is known as method overriding. In below example same method "show()" is present in both base and derived class with same name and signature.
Example of Method Overriding in C++
#include<iostream.h> #include<conio.h> class Base { public: void show() { cout<<"Base class"; } }; class Derived:public Base { public: void show() { cout<<"Derived Class"; } } int mian() { Base b; //Base class object Derived d; //Derived class object b.show(); //Early Binding Ocuurs d.show(); getch(); }
Output
Base class Derived Class
Run Time Polymorphism
In C++ Run time polymorphism can be achieve by using virtual function.