Introduction to Polymorphism

 

Polymorphism

Polymorphism is the ability to take different forms

It is the mechanism to use a function with same name in different ways

 

Virtual Functions

Virtual function is the member function of a class.

It can be overriden in its derived class

It is declared with virtual keyword

Virtual function call is resolved at run-time

 

Eg:

#include <iostream>
using namespace std;
 
class Parallelogram
{
  protected:
    int width, height, ar;
  public:
    void set_values (int a, int b)
      {
            width=a; height=b;
      }
      //creating virtual function
    virtual int area ()
      {
            ar=width*height;
            cout<< "Area of parallelogram is "<< ar<<"\n";
      }
};
 
class Rectangle: public Parallelogram
{
  public:
  //here area function reusing in different way
    int area ()
      {
            ar=width * height;
            cout<< "Area of rectangle is "<<ar <<"\n";
      }
};
 
class Triangle: public Parallelogram
{
  public:
    int area ()
      {
            ar=width * height / 2;
            cout<< "Area of triangle is "<< ar<<"\n";
      }
};
 
int main()
{
    Parallelogram *parallel, p;
    Rectangle rect;
    Triangle trgl;
 
    parallel=&p;
    parallel->set_values(3,2);
    parallel->area();
 
    parallel=&rect;
    parallel->set_values(4,5);
    parallel->area();
 
    parallel=&trgl;
    parallel->set_values(6,5);
    parallel->area();
 
return 0;
}

Output:-          Area of parallelogram is 6

Area of rectangle is 20

Area of triangle is 15

                                                        

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

0 Comments