C++ Polymorphism


Polymorphism is by far the most important and widely used concept in object oriented programming. Some of the widely used technologies and libraries like COM, MFC etc. have polymorphism as their foundation. If you look at all the original design patterns, almost every pattern uses polymorphism in its structure.

Polymorphism is a mechanism that allows you to implement a function in different ways.


Pointers to base class

We have seen that it is possible to derive a class from a base class and that we can add functionality to member functions.

One of the features of derived classes is that a pointer to a derived class is type-compatible with a pointer to its base class. Polymorphism takes advantage of this feature.

#include <iostream>
using namespace std;
class CPoly
{
	protected:
		int width, height;
	public:
		void setup (int first, int second)
		{
			width = first;
			height = second;
		}
};

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

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

int main ()
{
	CRectangle rectangle;
	CTriangle triangle;

	CPoly * ptr_polygon1 = &rectangle;
	CPoly * ptr_polygon2 = ?

	ptr_polygon1 ->setup(2,2);
	ptr_polygon2 ->setup(2,2);

	cout << rectangle.area () << endl;
	cout << triangle.area () << endl;

	return 0;
}

As you can see, we create two pointers (ptr_polygon1 and ptr_polygon2) that point to the objects of class CPolygon. Then we assign to these pointers the address of (using the reference ampersand sign) the objects rectangle and triangle. Both rectangle and triangle are objects of classes derived from CPolygon.


Virtual Members

A virtual member is a member of a base class that we can redefine in its derived classes. To declare a member as virtual we must use the keyword virtual.

#include <iostream> 
using namespace std;

class CPoly
{
	protected:
		int width, height;
	public:
		void setup (int first, int second)
		{
			width = first;
			height = second;
		}
		virtual int area()
		{
			return 0;
		}
}; 

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

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

int main ()
{
	CRectangle rectangle;
	CTriangle triangle;
	CPoly polygon; 

	CPoly * ptr_polygon1 = &rectangle;
	CPoly * ptr_polygon2 = ?
	CPoly * ptr_polygon3 = &polygon;

	ptr_polygon1 -> setup(2,2);
	ptr_polygon2 -> setup(2,2);
	ptr_polygon3 -> setup(2,2);

	cout << ptr_polygon1->area() << endl;
	cout << ptr_polygon2->area() << endl;
	cout << ptr_polygon3->area() << endl;

	return 0;
}

Share this article on