Google

Pure Virtual Functions in C++

Written on:May 28, 2013
Comments are closed




Pure Virtual Functions in C++

A Pure Virtual Function is a virtual function that is initialised to zero and has no definition in the base class.  Such functions are merely included in the base class, but do not perform any task.  A pure virtual function is also referred to as a do-nothing function.  Such a function is defined separately in all derived classes and its definition in the base class is not required.  The compiler, in case of a pure virtual function, requires each derived class to either define the function or re-declare it as a pure virtual function.  Such a class which contains a pure virtual function cannot be instantiated,  is referred to as an abstract class.


Consider the following code segment:

class base
{
public:
virtual void show_output() = 0;
//a pure virtual function declared
//and initialized to zero.
};

class derived : public base
{
public:
void show_output()
//function re-defined in derived class.
{
cout<<”Inside show_output function.”;
}
};

As the presence of a pure virtual function in a class requires that it should be implemented in derived classes, in the above code segment show_output() function in class ‘base’ is defined as virtual and is initialized with zero, so it is a pure virtual function.  Class ‘derived’ is publicly inherited from class ‘base’.  Class ‘base’ is an abstract base class, as it includes a pure virtual function.

 

Sorry, the comment form is closed at this time.