In C++ a concept called polymorphism is used to allow a single entity to behave differently in different situation.
Here I am talking about runtime polymorphism or Virtual functions. Usually when we do a normal function call, at the compile time itself , relative address of that function is known. So the function call is binded with the function body which is going to be executed.
Virtual functions allows one to decide which function to call at runtime. so the call binding is done at runtime.
Have a look at following code it have three classes , class B & C is derived from class A. We have a single virtual function “Display” in base class which is overridden in derived class B & C.
Here we are calling function Display using base class pointer. So based on the object hold by base class pointer, function from respective class is called.
#include “stdafx.h”
#include <iostream>
#include <string>
using namespace std;class A
{
public:virtual void Display(){ cout << ” A::Display ” << endl;}
};
class B:public A
{
public:
void Display(){ cout << ” B::Display ” << endl;}};
class C:public B
{
public:
void Display(){ cout << ” C::Display ” << endl;}
};int main(int argc, char* argv[])
{
A *pBasePtr = NULL;
pBasePtr = new A();
pBasePtr->Display();
pBasePtr = new B();
pBasePtr->Display();
pBasePtr = new C();
pBasePtr->Display();
return 0;
}


