Friday, 9 December 2011

Concept of Polymorphism

/*Polymorphism: a greek term means "ability to take more than one form", i.e.. any operation may exhibit different behaviours in different instances.
Behaviour depends on the following:
i)  types of parameter passed
ii) number of parameter passed
iii)order of the parameter passed

Different types of polymorphism are:

a)COMPILE TIME Polymorphism(Static polymorphism)->
  Example:
  1)Function overloading(same function name performs different tasks)
  2)Operator overloading(mechanism of assigning special meanings to operator,(Sizeof)(.)(.*)(::)(?:)cannot be overloaded)

b)RUN TIME Polymorphism(Dynamic polymorphism)->    eg. Virtual function                */

/* Program to implement compile time polymorphism*/
#include<iostream.h>
#include<conio.h>
class Add
{
int x,y,z;
public:
void getdata(int a,int b,int c);
void display(void);

//Declaration(prototypes)
int sum(int,int,int);                                //function sum is overloaded
double sum(double,int,double);           //function sum is overloaded

//Declaration(no prototype)
void operator-();                                     //overload unary minus
};

void Add::getdata(int a,int b,int c)
{
x=a;
y=b;
z=c;
}

//Function Definations
int sum(int a,int b,int c){
return(a+b+c);
}
double sum(double a,int b, double c){
return(a+b+c);
}

void Add::display(void)
{
cout<<x<<" ";
cout<<y<<" ";
cout<<z<<"\n";
}
//operator definationvoid Add::operator-()
{
x=-x;
y=-y;
z=-z;
}

void main()
{
clrscr();
Add a1;
a1.getdata(2,-3,-4);
cout<<"Input:";
a1.display();
-a1;                                                     //activates operator-() function
cout<<"operator -() Output:";
a1.display();
cout<<"Function output sum(2,3,4): "<<sum(2,3,4)<<"\n";
cout<<"Function output sum(1.5,2,2.2): "<<sum(1.5,2,2.2);

getch();
}

OUTPUT:

1 comment: