Virtual Function: A virtual function is a member function that is declared within a base class and redefined by its derived class. When base class and its derived class both contain same name member function then derived class function overrides base class function. Base class pointer is used to refer member functions of its class as well as its derived class. When base pointer is used to refer to functions, it ignores the contents of the pointer and selects the member function that matches the function call. To execute derived class version of the overridden function virtual keyword is used with base class function. When a function is made virtual, compiler checks the address stored inside the pointer. If the pointer points to base class then function from base class is executed. If it contains address of derived class then function from derived class is executed. Run time polymorphism requires virtual function to execute same name function from base class and derived class depending on address stored inside the pointer.
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,*bptr;
Derived D;
bptr=&B;
bptr->show( );
bptr=&D;
bptr->show( );
}
In above example, both base and derived class contains same name function as show. By creating a pointer of base class one can invoke desired show function by storing address of respective object in pointer.