Pure Virtual Function and Abstract Class
In the below code, the SHAPE class has a pure virtual function and is an abstract class (cannot be instantiated). Each class is derived from SHAPE implementing Draw () function in its own way.

Further, each Draw function is virtual so that when we use a base class (SHAPE) pointer each time with the object of the derived classes (Circle and SQUARE), then appropriate Draw functions are called.

#include <iostream.h>
#include <conio.h>

class Shape    // abstract class
{
	public:
	void virtual draw()=0 ;  //pure virutal function
};

class Triangle : public Shape
{
	public:
	void draw()
	{
			cout<<"I am Traingle"<<endl;
	}
};

class Rectangle: public Shape
{
	public:
	void draw()
	{
		cout<<"I am Rectangle"<<endl;
	}
};


void main()
{
	clrscr();

	Shape *ps;

	Triangle t;
	Rectangle r;
	ps=&t;
	ps->draw();
	ps=&r;
	ps->draw();
	getch();
}

Pure Virtual Function and Abstract Class with Shape, Rectangle and Triangle Example

Leave a Reply

Your email address will not be published. Required fields are marked *