Polymorphism

Polymorphism is the combinstion of two greek word one is 'poly' means many and another is 'morphism' means forms that means When one task is performed by different ways i.e. known as polymorphism.

Example:

Let's take a simple example in which as you can see that class name is poly and there are four function with same name fun() with diffrent parameter so execution of function is based on the value passing at the time of calling.

#include< iostream.h >
class poly
{
public:
void fun()
{
cout<< "no parameter " << "\n"<< a;
}
void fun(int a)
{
cout<< "Integer parameter " << "\n"<< a;
}
void fun(float b)
{
cout<< "float parameter " << "\n"<< a;
}
void fun(char ch)
{
cout<< "character parameter " << "\n"<< a;
}
};
void main()
{
poly obj1; // create object
obj1.fun(12); // passing integer value
obj1.fun('A'); // Passing character value
}

Output:

Integer parameter
character parameter

Here function is called two times first time with integer value and the second time with character value.

Type of polymorphism

  • Compile time polymorphism
  • Run time polymorphism

Compile time polymorphism

Compile time polymorphism means method are binding with an object at compile time is called Compile time polymorphism.

Example: method overloading

Run time polymorphism

Run time polymorphism means method are binding with an object at run time is called Run time polymorphism.

Example: method overriding

Function Overlaoding

In function overloading we declare more than one function with same name and diffrent parameter is called function overloading.

#include< iostream.h >
class geometry
{
public:
void area(int heigh, int width)
{
int ar=height*width;
cout<< "Area of ractangle =" << ar <<"\n";
}
void area(int side)
{
int ar=side*side;
cout<< "Area of squre =" << ar <<"\n";
}
};
void main()
{
geometry obj1; // create object
obj1.area(12,13); // passing two parameter
obj1.area(12); // Passing single parameter
}

Output:

Area of ractangle =156
Area of squre =144

Here geometry is class name contains two function with the same name area() with diffrent parameter, first with two parameter height and width and second with single parameter side. Therefore when two integer parameter is passed at the time of calling Rectangle area will be calculated, when single integer parameter is passed squre area will be calculated.