I was recently reading an article in the bitsquid blog about how to manage memory and the author began to talk about the vtable and how there is a pointer added to the class by the compiler. Here is the link for the article. So because I hardly knew anything about the vtalbe I began to search the web for an explanation. I came accross this link. Based on what I read I made the following code:
char cache[24];
printf("Size of int = %d\n", sizeof(int));
printf("Size of A = %d\n", sizeof(A));
A* a = new(cache)A(0,0);
printf("%s\n",cache);
printf("vTable : %d\n",*((int*)cache));
printf("cache addr: %d\n",&cache);
int* funcPointer = (int*)(*((int*)cache));
printf("A::sayHello: %d\n",&A::sayHello);
printf("funcPointer: %d\n",*funcPointer);
A is a class with two integers members and a virtual function sayHello().
EDIT : Here is the class definition:
class A {
public:
int _x;
int _y;
public:
A(int x, int y) : _x(x), _y(y){ }
virtual void sayHello() { printf("Hello You!"); }
};
Basically what I was trying to do is see if the pointer inside the vtable would point to the same place as where the address I get from &A::sayHello, but the thing is that when I run the program, the address inside the pointer in the vtable and the sayHello() address always has a difference of 295. Does anyone know why this could be happening? Is there some kind of header that’s added that I’m missing? I’m running visual studio express 2008 on a 64 bit machine.
From what I have debugged the address that is returned by *funcPointer is the true address of the function sayHello(). But why is the &A::sayHello() returning a different address?
C++ has an interesting feature :
If you take a pointer to a virtual function and use it, the virtual function will be resolved and called.
Let’s take a simple example
So, the address you see using
&A::DoSomethingis the address of the trampoline, not the real function address.If you go to assembly, you’ll see that function does something like that (register may change but ecx which represent the this pointer ):