Wednesday 3 September 2014

POLYMORPHISM

POLYMORPHISM

Poly means many and morphism means forms . When yoy are performing multiple tasks with one name then the whole concept is known as polymorphism.
In Polymorphism we study two concept.
  1. Function overloading
  2. Function overriding

Function Overloading

In Function Overloading, We have a class in which functions are defined with same name but different arguments but their signature is different .Signature means return type function. All the Functions are called according to the no. of arguments they contain .This whole concept is known as Function Overloading.It is also called Design Time Polymorphism. Lets take a example.
 
#include<iostream.h>
#include<conio.h>
 
class ABC
{
 
public:
 
int add(int a, int b)
{
return(a*b);
}
 
int add(int a, int b, int c)
{
return(a*b*c);
}
 
int add(int a, int b, int c, int d)
{
return(a*b*c*d);
}
 
};
 
void main()
{
ABC t;
int k;
k=t.add(30,40);
cout<<k;
 
k=t.add(40,50,90);
cout<<k;
 
k=t.add(20,50,70,80);
cout<<k;
 
getch();
}
 

Function Overriding

It is the concept which is also uses the concept of Virtual Function. Suppose there are two classes A and B and B is the derived class of A in both classes. We have the function with same name but because the class function is declared virtual and whenever we create the object of derived class and calls the function the control first goes to the base class then it comes back to the derived class it is because the base class function is declared virtual and it can be called only by the object of the class in which it has been declared so, Derived class function will be executed. This whole procedure is termed Function Overriding.It is also called as Run time Polymorphism. Lets see a example of it
 
 
#include<iostream.h>
#include<conio.h>
 
class A
{
int a, b, c;
 
public:
 
virtual void get()                               // Virtual Function declared
{
cout<<"Enter the numbers";
cin>>a>>b;
c=a*a + b*b;
cout<<c;
}
};
 
class B : class A
{
int  i, j, k;
{
 
public:
 
void get()
{
cout<<"Enter the numbers";
cin>>i.>>j;
k=i*i + j*j + i*i +j*j;
cout<<k;
}
 
};
 
void main()
{
result r;
r.get();
info f;
f.get();
getch();
}
 
 

No comments:

Post a Comment