Posted By:
4 Jul, 2013 11:03 am PDT

Polymorphism in C++

What is polymorphism?

The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance. C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.


The simplest form of polymorphism is overloading of function. In OOP, polymorphism is done by making a function virtual in the base class and then over riding it in the derived class.



#include <iostream.h>

             class Polygon



                       int width, height;


                       void set_values (int a, int b)

                     { width=a; height=b; }

                    virtual int area ()

                     { return (0); }


             class Rectangle: public Polygon



                 int area ()

                 { return (width * height); }


           class Triangle: public Polygon



                 int area ()

                 { return (width * height / 2); }


           void main ()


                   Rectangle rect;

                   Triangle trgl;

                   Polygon poly;

                   Polygon * ppoly1 = ▭

                   Polygon * ppoly2 = &trgl;

                 Polygon * ppoly3 = &poly;

                 ppoly1->set_values (4,5);

                  ppoly2->set_values (4,5);

                 ppoly3->set_values (4,5);

                 cout << ppoly1->area() << endl;

                 cout << ppoly2->area() << endl;

                 cout << ppoly3->area() << endl;



Now the three classes (Polygon, Rectangle and Triangle) have all the same members: width, height, set_values() and area(). The member function area() has been declared as virtual in the base class because it is later redefined in each derived class. You can verify if you want that if you remove this virtual keyword from the declaration of area() within Polygon, and then you run the program the result will be 0 for the three polygons instead of 20, 10 and 0. That is because instead of calling the  corresponding area() for each object, Polygon::area() will be called in all cases since the calls are via a pointer whose type is Polygon*.

Was it useful?  

Please login to reply to this problem.