Polymorphism in C++

Polymorphism

  • Polymorphism word is derived from 2 greek words Poly and Morphs which means many forms.
  • Polymorphism means having multiple forms.
  • It is done by method overriding when both super class(Base class) and sub class (Parent class) have same member function but with different definition.
  • Method overriding is called when two or more methods (functions) have exactly same method name, return type, number and types of parameters as the method in the parent class.
  • Method overriding cannot be done within a class. It requires a base class and a derived class.

Example : Program demonstrating Method Overriding

#include<iostream>
using namespace std;
class BaseClass
{
     public:
         int display()
         {
              cout <<"Super Class\t";
         }
};
class DerivedClass:public BaseClass
{
     public:
         int display()
         {
              cout <<"\n Sub Class";
         }
};
int main()
{
     BaseClass b;           //Base class object
     DerivedClass d;     //Derived class object
     b.display();          //Early Binding Occurs
     d.display();   
}


Output:
Super Class
Sub Class

In the above program, display() function is overridden in the derived class. BaseClass's object b calling base class version of the function and DerivedClass's object d calling derived version of the function.