A virtual function is a member function which is defined in Base class and redefined by the derived class. “virtual” keyword must be added before the function declaration to define a function virtual. These functions gets inherited by Derived class from Base class and Derived class can choose to provide it’s own definition.
A pure virtual function is a virtual function which has no definition in Base class. Pure virtual function definition is used to ensure all derived class must override the base class function definition.
Normal syntax to define virtual function is as follows:
virtual int samplefun (int x, char c);
Important Points
- Virtual functions can’t be static function.
- Friend function can’t be defined as virtual.
- Constructors can’t be virtual, but destructors can virtual.
- “virtual” keyword not needed to be added in function declaration inside Derived class.
- virtual functions help in identifying the correct version of function to be invoked in case Derived object is pointed by Base class pointer at run-time. This phenomenon is called Late Binding or Run-Time Binding.
- Derived class doesn’t need to redefine virtual class. In case derived class definition is missing then Base class function is invoked.
Let’s have a look at the sample program to understand it better.
#include <iostream>
using namespace std;
class Base
{
public:
virtual ~Base ()
{
cout << "Inside Base Destructor." << endl;
}
virtual void print ()
{
cout << "Base version called." << endl;
}
};
class Derived:public Base
{
public:
virtual ~Derived ()
{
cout << "Inside Derived Destructor." << endl;
}
void print () /* virtual keyword not needed */
{
cout << "Derived version called." << endl;
}
};
int main ()
{
Base *p = new Derived ();
p -> print ();
delete p;
p = new Base ();
p -> print ();
delete p;
}
Let’s analyze the output of above program.
Derived version called.
Inside Derived Destructor.
Inside Base Destructor.
Base version called.
Inside Base Destructor.
Pure Virtual Function
A pure virtual function is a virtual function which has no definition in Base class. Derived class must override the base class pure virtual function definition else compiler will throw compile time error. Hence, pure virtual function mandates compulsory override of virtual function by derived class.
Normal syntax to define pure virtual function is,
virtual void pure_virtual_fun () = 0;
Important Points
- Compiler will throw compile time error in case derived class doesn’t override the virtual function.
- Abstract Class is a class which has one or more pure virtual function declaration.
- Compiler will throw compile time error in case program tries to create abstract class object.