C++ :Polymorphism | Pure Virtual Functions

Pure Virtual Functions

A Virtual function defined inside the base class normally serves as a framework for the future design of the class hierarchy.

These functions can be overridden by the methods in the derived class. These functions are defined with NULL body i.e. it has no definition.

Such functions in the base class are similar to do nothing functions or dummy functions. In “C++” these are called as pure virtual functions.

Syntax:
class baseclass
{
statements
public:
virtual returntype functionname(list of arguments)=0;
statements
};

• A pure virtual function declared in the base class has no implementation as far as base class.

• The classes derived from a base class having a pure virtual function has to declare a function with the same name as pure virtual function declared in the base class.

• Definition of such function has to be given in derived class only.

• It must be noted that a class containing a pure virtual function cannot be used to declare an object of its own, if we try to do so an error will get generated.

• Class containing pure virtual functions is called a pure abstract class or simply abstract class.

• Whereas all the other classes without pure virtual functions are called concrete classes.

• A pure virtual function is an unfinished placeholder which the derived class is expected to complete.

Example of pure virtual function / method overriding

//virtual1.cpp
#include<iostream>
#include<conio.h>
using namespace std;
class sample
{
	public:
		virtual void abc(int n);   //normal virtual function
		virtual void pqr(int n)=0; // pure virtual function
};
class hello:public sample
{
	public:
		void pqr(int n);
};
void sample::abc(int n)
{
	pqr(n);
}
void hello::pqr(int n)
{
	cout<<"value of n is "<<(60-n)<<endl;
}
int main()
{
	//sample s1; will generate error
	hello a1,a2;
	a1.abc(50);//1
	a2.pqr(20);//2
	getch();
	return(0);
}

Output:

value of n is 10
value of n is 40

Note:
Normally a base class member function is called from within the derived class member function.

But when derived class member function gets called from within the base class member function this is called method overriding, as it overrides the normal flow of control.

a1.abc();
The base class member function abc() is invoked using the object of derived class which is allowed. Now from within the abc() function pqr() function is called but we do not have the definition of pqr() function in the base class, so the pqr() function of the derived class gets called which is overriding the flow of control thus it is known as function / method overriding.