AIM: Write a C++ program to illustrate runtime polymorphism.
THEORY:
The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.
Real life example of polymorphism, a person at a same time can have different characteristic. Like a man at a same time is a father, a husband, a employee. So a same person posses have different behavior in different situations. This is called polymorphism.
Polymorphism is considered as one of the important features of Object Oriented Programming.
In C++ polymorphism is mainly divided into two types:
- Compile time Polymorphism
- Runtime Polymorphism
SOURCE CODE:
#include<iostream>
using namespace std;
float add(float m,float n)
{
return m+n;
}
float sub(float m,float n)
{
return m-n;
}
float mul(float m,float n)
{
return m*n;
}
int main()
{
float x,y;
cout<<” Enter two numbers:\n”;
cin>>x>>y;
int task;
do
{
cout<<”Enter task(1=add,2=sub,3=mul,4=exit): “;
cin>>task;
float(*pt)(float,float);
switch(task)
{
case 1: pt=add;
break;
case 2: pt=sub;
break;
case 3: pt=mul;
break;
case 4: exit(0);
break;
default: cout<<“You entered a wronge option\n”;
}
cout<<“Result of operation is:”<<pt(x,y)<<endl;
}while(task<5 && task>0);
return 0;
}
OUTPUT:
Enter two numbers:
96 65
Enter task(1=add,2=sub,3=mul,4=exit): 3
Result of operations is: 6240
Enter task(1=add, 2=sub, 3=mul, 4=exit): 2
Result of operation is: 31
Enter task(1=add, 2=sub, 3= mul, 4=exit): 4