Submit Your Site To The Web's Top 50 Search Engines for Free!       ExactSeek: Relevant Web Search


Flag Counter

Total Pageviews

Wednesday, January 30, 2013

Polymorphism in C++

Before getting into this section, it is recommended that you have a proper understanding of pointers and class inheritance. If any of the following statements seem strange to you, you should review the indicated sections:

Explained in:
int a::b(c) {};
Data Structures
class a: public b;
Friendship and inheritance

Pointers to base class

One of the key features of derived classes is that a pointer to a derived class is type-compatible with a pointer to its base class. Polymorphism is the art of taking advantage of this simple but powerful and versatile feature, that brings Object Oriented Methodologies to its full potential.

We are going to start by rewriting our program about the rectangle and the triangle of the previous section taking into consideration this pointer compatibility property:

// pointers to base class    20
#include <iostream>    10
using namespace std;

class CPolygon {
          int width, height;
          void set_values (int a, int b)
               width=a; height=b; 

class CRectangle: public CPolygon {
           int area ()
               return (width * height); 

class CTriangle: public CPolygon {
           int area ()
               return (width * height / 2); 

int main () { 
    CRectangle rect; CTriangle trgl;
    CPolygon * ppoly1 = &rect; 
    CPolygon * ppoly2 = &trgl;     
    ppoly1->set_values (4,5); 
    ppoly2->set_values (4,5); 
    cout <<  rect.area() << endl; 
    cout << trgl.area() << endl; 
    return 0;

In function main, we create two pointers that point to objects of class CPolygon (ppoly1 and ppoly2). Then we assign references to rect and trgl to these pointers, and because both are objects of classes derived from CPolygon, both are valid assignment operations.

The only limitation in using *ppoly1 and *ppoly2 instead of rect and trgl is that both *ppoly1 and *ppoly2 are of type CPolygon* and therefore we can only use these pointers to refer to the members that CRectangle and

CTriangle inherit from CPolygon. For that reason when we call the area() members at the end of the program we have had to use directly the objects rect and trgl instead of the pointers *ppoly1 and *ppoly2.

In order to use area() with the pointers to class CPolygon, this member should also have been declared in the class CPolygon, and not only in its derived classes, but the problem is that CRectangle and CTriangle implement different versions of area, therefore we cannot implement it in the base class. This is when virtual members become handy:


Post a Comment