When base class and its derived class both contains same function name then the function in base class is declared as virtual using keyword virtual preceding its normal declaration. When a function is made virtual, C++ determines which function to use at run time based on the type of object pointed to by the base pointer, rather than the type of the pointer. Thus by making the base pointer to point to different objects we can execute different versions of the virtual function.
Example:
#include<iostream.h>
class Base
{
public:
virtual void show( )
{
cout<<”\n show base”;
}
};
class derived : public Base
{
public:
void show( )
{
cout<<”\n show derived”;
}
};
void main( )
{
Base B;
derived D;
Base *bptr;
bptr=&B;
bptr->show( );
bptr=&D;
bptr->show( );
}