In order to achieve polymorphism, objects belonging to different classes should be able to respond to the same message at different instances which initiates the use of single pointer variable to refer to objects of different classes. In case of inheritance, base class pointer is used to refer to all derived objects but even when it contains an address of derived class always executes base class function. The Compiler simply ignores content of pointer & selects member function that matches type of pointer. In order to achieve polymorphism, the concept of virtual functions is used. When we use same function name in both base & derived classes, function in base class is declared as virtual using keyword virtual preceding its normal declaration. When function is made virtual C++ determines which function to be executed at runtime based on type of object pointed to by base pointer rather than type of pointer. Thus by making use of single pointer variable (base pointer) to point to different objects so that different version of virtual function can be executed and hence polymorphism is achieved known as Run Time Polymorphism.
Example:
#include<conio.h>
#include<iostream.h>
class student
{
int roll;
char name[20];
public:
virtual void accept()
{
cout<<"\n Enter Roll id:";
cin>>roll;
cout<<"\n Enter name:";
cin>>name;
}
virtual void display()
{
cout<<"\n Roll id:"<<roll<<endl;
cout<<"\n Name:"<<name<<endl;
}
};
class Test: public student
{
int marks1,marks2;
public:
void accept()
{
student::accept();
cout<<"\n Enter marks 1:";
cin>>marks1;
cout<<"\n Enter marks 2:";
cin>>marks2;
}
void display()
{
student:: display();
cout<<"Marks1="<<marks1<<endl;
cout<<"Marks2="<<marks2<<endl;
}
};
void main()
{
student *p;
Test b;
p=&b;
clrscr();
p->accept();
p->display();
getch();
}