Virtual function is a function which is a member of a class, the functionality of
which can be over-ridden in the derived classes.
A D V E R T I S E M E N T
It is declared as a virtual in the
base class using the keyword virtual. Virtual nature is been inherited in the
subsequent derived classes and there is no need to re-state virtual keyword.
Whole function body can be replaced by the new set of implementation in a
derived class.
The code given below shows how virtual function in C++ can be used
to achieve the dynamic or the runtime polymorphism.
#include <iostream.h>
class base
{
public:
virtual void display()
{
cout<<�\nBase�;
}
};
class derived : public base
{
public:
void display()
{
cout<<�\nDerived�;
}
};
void main()
{
base *ptr = new derived();
ptr->display();
}
In the example above, pointer is of the type base but it points to derived
class object. A display() method is virtual in the nature. Therefore to resolve
a virtual method call, context of a pointer is been considered, Which means that a
display method of derived class is been called and not the base class. If a method was
non virtual in nature, a display() method of base class might have been called up.