Polymorphism
The word polymorphism means one name many forms. It means there can be more then one function with same name in a program as long as it follows polymorphism rules.
Real life example of polymorphism is a person has only one name but can perform different task and shows different characteristic in different situations.
In Object Oriented programming polymorphism is of two types.
1. Compile Time Polymorphism
2. Run Time Polymorphism
Compile Time Polymorphism
Compile time polymorphism is achieved through function overloading and operator overloading.
1. Function Overloading
When there are more then one function with same name but different number and type of arguments in a class or program then it is called function overloading.
A function can be overloaded by changing number and type of arguments in argument list.
Example
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class Check
{
public:
//Function with one int type argument
void func(int x)
{
cout<<"\nOne argument function called x:"<<x;
}
//Function with two int type arguments
void func(int x,int y)
{
cout<<"\nTwo argument function called x:"<<x<<" y:"<<y;
}
//Function with double type argument
void func(double x)
{
cout<<"\nDouble argument function called x:"<<x;
}
};
void main()
{
clrscr();
Check c;
c.func(1.2);
c.func(10);
c.func(20,30);
getch();
} |
Output
Double argument function called x:1.2
One argument function called x:10
Two argument function called x:20 y:30 |
2. Operator Overloading
Operator overloading is an example of compile time polymorphism in Object Oriented Programming. An operator can perform multiple tasks at a time like adding two integers and performing concatenation of two strings.
Example
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class Check
{
private:
float x,y;
public:
void setData(int a,int b)
{
x=a; y=b;
}
void getData()
{
cout<<"\nx:"<<x<<" y:"<<y;
}
};
//Defining an operator function + to overload
Check operator +(Check c)
{
Check temp;
temp.x=x+c.x;
temp.y=y+c.y;
return temp;
}
void main()
{
clrscr();
Check c1,c2,c3;
c1.setData(10,20);
c2.setData(11,12);
c3=c1+c2;
c3.getData();
getch();
} |
Output
Run Time Polymorphism
Compile time polymorphism is achieved through function overriding.
Function Overriding
Function overriding occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.
Example
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class Baseclass
{
public:
//Declaration of virtual function
virtual void display()
{
cout<<"\nBaseclass\n";
}
};
class Childclass:public Baseclass
{
public:
void display()
{
cout<<"\nChildclass\n";
}
};
void main()
{
clrscr();
//Creating pointer of baseclass
Baseclass *p,b;
Childclass c;
p=&c;
p->display();
p=&b;
p->display();
getch();
} |
Output
For more Object Oriented Programming Lab Experiments Click Here