When base class and its derived class both contain same name and prototype 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. When both the classes contain same name and prototype function, base pointer executes a function from base class without considering the address inside the pointer. 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 gets executed. If it contains address of derived class then function from derived class gets 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.
Program/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( );
}
As given in above example, both base and derived class has same function named as show. By creating a pointer object of base class one can invoke desired show function by adjusting pointer position.