Virtual Mechanism

The keyword virtual tells the
compiler it should not perform early binding. Instead, it should automatically
install all the mechanisms necessary to perform late binding.

To accomplish this, the
typical compiler1 creates a single table (called the VTABLE) foreachclass that contains virtual
functions.The compiler places the addresses of the virtual
functions for that particular classin the VTABLE.
In each class with virtual
functions,it secretly places a pointer, called the vpointer (abbreviated as
VPTR), which points to the VTABLE for that
object.

When you make a virtual
function call through a base-class pointer the
compiler quietly inserts code to fetch the VPTR and look up the function
address in the VTABLE, thus calling the correct function and causing late
binding to take place.

Virtual:

#include<vector>

#include<string>

#include<iostream>

usingnamespace std;

class Shape

{

public:

virtualvoid draw(){cout<<"Shape
draw"<<endl;}

};

class Rectangle:public Shape

{

public:

void draw(){cout<<"Rectangle
draw"<<endl;}

};

class Circle:public Shape

{

public:

void draw()

{

cout<<"Circle draw"<<endl;

}

};

int _tmain(int argc, _TCHAR* argv[])

{

vector<Shape
*> shapelist;

Shape *s;

int choice = 1;

cout<<"enter 1 for rectangle ,2 for circle,0 for
exit"<<endl;

while(choice>0)

{

cin>>choice;

if(choice == 1)

{

Rectangle
R;

s=&R;

shapelist.push_back(s);

}

elseif(choice == 2)

{

Circle
C;

s=&C;

shapelist.push_back(s);

}

else

break;

}

for(int i
=0;i<shapelist.size();i++)

{

shapelist[i]->draw();

}

return 0;

}

Run-time polymorphism: Definition: Keeping the behaviour
constant and switching the implementation at run-time is called Run-time
polymorphism.

Virtual Mechanism:

-Compiler creates a v-table for each class that has atleast
one virtual function.

-Only one v-table is created for each class irrespective of no
of objects.