Tuesday, September 27, 2005

Virtual Functions

One of the most common interview questions for a c++ programmer is the virtual function.I beleived i knew how virtual function worked until i saw this article at code project.
ATL

Here is the jist
class Base {
int i;
virtual void fun() {cout << "Base:fun()" <<>
};

Base baseobj;
sizeof(baseobj) = 8;

Memory Structure of BaseObj
0th position : virtual pointer which points to the vtable, the vtable in turn points to the virtual function.
1st position is the integer.

&objBase = address of objBase;

&objBase +0 = address of the first element of the objBase which is the virtual pointer here.

(int*) (&objBase + 0)
since its a pointer we have to typecast it to (int *) to print its value.

*(int *)(&objBase + 0)
value at virtual pointer of objBase = address of vtable.

(int*) *(int*)(&objBase + 0)
since the value is also an address we have to type cast it to (int *).

Now if you want to point to the function
typedef void (*Fun)(void);

Fun pFun = (Fun)*(int*)*(int*)(&objClass+0);
value at the first entry in the virtual table is type cast to the function pointer.

so that you can do pFun();

Calling virtual function within the base class.

class Base {
virtual void fun() {cout << "Base:fun()" << endl;}
Base() { fun(); }
};

class Derived :: Base {
virtual void fun() {cout << "Derived:fun()" << endl;}
};

main()
{
Base*p = new Derived();
}

will print Base:fun because the constructor is responsible for creating the vtable and assigning the address of the vtable t the vpointer. In the constructor of the base class, the vpointer points to the vtable which has the base function. When the derived class constructor is called through the chain. A new vtable is created and the vpointer now points to the derived class vtable which in turn points to the derived class function.Thats why with in the base class constructor the base class virtual function is called.

0 Comments:

Post a Comment

<< Home