Thursday, September 14, 2006

Virtual function mechanism

Tips :
Virtual function mechanism is key feature of C++ for dynamic binding.
Whenever a class declares a virtual function or is derived directly or indirectly from a class which declares a virtual function, the complier adds an extra hidden member variable which points to the virtual table. A virtual table is nothing but an array of pointers to the virtual functions. The entries in the virtual table are changed at run time to point to the correct function.

while allocating memory for a class, the first four bytes are pointer to the virtual table. The virtual table itself contains pointers to the virtual functions of the object.
So what we were doing in the program is changing the address of the virtual table pointer to the fn MyFunc() ...


we try to change the address of the virtual function pointer in the following program:


#include
#include
#include
//Pointer to a function returning void

typedef void (*PFN)();
typedef struct
{
PFN Fn;
} VTable;

void MyFunc()
{
cout<<"\n This is MyFunc() \n";
}

//Base class
class CBase
{
public:
virtual void Display() {
cout<<"\n CBase :: Display() function \n";
}
};


//Derived class

class CDerived :public CBase{
public :
void Display() {
cout<<"\n CDerived :: Display() function \n";
}
};

int main(int argc, char* argv[]){

CDerived derivedObj;
CBase *pBase =&derivedObj;

//Create our own VTable
VTable myOwnTable ;
//Pointer to Fn MyFunc()

myOwnTable.Fn = MyFunc;
//Holder for pointer to virtual table
VTable *pVTable = &myOwnTable;

//Tweak the virtual table pointer by changing the first 4 bytes (assuming a long holds pointer)
memcpy(&derivedObj, &pVTable , sizeof(long));

pBase->Display();

getch();
return 0;

}

No comments: