Abstract Class and Pure Virtual Function

Abstract Class and Pure Virtual Function

An Abstract class is a class that has at least one pure virtual function. A pure virtual function is a function without definition. To declare pure virtual function use the following syntax:

virtual return-type function-name(parameter-list) = 0;

For example, we can modify above baseClass to make it abstract class:

class baseClass
{
public:
	baseClass(int val) :someValue(val)
	{

	}
	//pure virtual function
	virtual void info() = 0;
protected:
	int someValue;
};

Now, info() is a pure virtual function. In this case when you use a pure virtual function then you must override it in the derived classes. You cannot create an object of the abstract class, but you can still use pointers of a base class to point an objects of the derived class.

Pure Virtual Destructor

As we know that, pure virtual functions are functions those are not defined (implemented). If a class has at least one pure virtual function, it becomes abstract.

C++ provides possibility to create pure virtual destructors. Pure virtual destructor also makes a class an abstract class, but there is a difference between pure virtual function and pure virtual destructor. Pure virtual destructor must be implemented:

class A
{
public:
	virtual ~A() = 0;
};

A::~A()
{
	cout << "Base class destrctor" << endl;
}

Pure Virtual Function with Function Body

Yes we can have a pure virtual function with a body as shown below

class Base
{
   	int x;
public:
    	virtual void fun() = 0
	{
		cout<<"Base Class fun() is Called";
	}
    	int getX() 
	{ 
		return x; 
	}
};
 
class Derived: public Base
{
    	int y;
public:
    	void fun() 
	{ 
		cout << "Derived Class fun() called"; 
	}
};
 
int main(void)
{
    	Derived d;
    	d.fun();
	//Calling Base Class Pure Virtual Function fun()
	Base::fun();
    	return 0;
}

To call Pure Virtual Function we should use the class name Class_Name::Function_Name

Use of Pure Virtual Function with a function body

Sometimes if you want to call base class function which is having the common functionality to be called in derived classes then instead of rewriting same logic multiple times we can write common logic in pure virtual function’s body.

 

Translate »