What is a Pure Virtual Function?

A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have an implementation, we only declare it. A pure virtual function is declared by assigning 0 in the declaration

pure-virtual-function

What is an Abstract Class?

 

An abstract class is a class that you cannot instantiate; you must extend it in order to use it. Only the methods that you extend, will be available in the child class. But why is this useful? Because sometimes you want to ensure that a class, or a set of classes, must implement as set of methods and must have access to a set of properties.

For example, you may create an abstract class called Vehicle, which will be the basis of any child class that describes a vehicle (cars, tanks, ships…etc.). This class ensures that every child class will have a drive(), stop(), and park() methods. It’s up to those classes to provide their own implementation of those methods, hence they will be created with empty bodies.

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

class Vehicle    // abstract class
{
	public:
	int chno;
	void virtual drive()=0 ;  //pure virutal function
};

class Car :  virtual public Vehicle    //virtual base class
{
	public:
	int b;
	void drive()
	{
		cout<<"I am driving Car"<<endl;
	}
};

class Truck: virtual public Vehicle
{
	public:
	int c;
	void drive()
	{
		cout<<"I am driving Truck"<<endl;
	}
};

class Trav :  public Car, public Truck
{
      public:
      int d;
      void drive()
      {
		cout<<"I am driving Trav"<<endl;
	}

};


void main()
{
	clrscr();

	Vehicle *pv;
	Car c;
	Truck t;
	Trav r;

	pv=&c;
	pv->drive();  //late binding
	pv=&t;
	pv->drive();
	r.chno=11;

	getch();
}

Pure Virtual Function and Abstract Class with Vehicle Example

Leave a Reply

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