tags:

views:

127

answers:

3

Hi all, i wanted to know how vptr getting vtable base address.

for instance

class A
{
virtual getdata();
int a;
}

now,

A obj; /// here vptr getting vtable's base address.

i wanted to know this mystery.. Thanks in advance

+1  A: 

The vptr is initialised by compiler-generated code as part of the initialisation of obj. There's no magic here, it just assigns it like so:

struct __A_vtbl_def {
    void (*getdata)(__A*);
};

__A_vtbl_def __A_vtbl = {
    &A__getdata
};

struct __A {
    __A_vtbl_def* vptr;
    int a;
};

__A obj;
obj.vptr = &__A_vtbl;

Note: This is all pretend code showing how a compiler might implement the vptr. I have no idea what actual code compilers spit out these days.

Marcelo Cantos
+1  A: 

This is no C++ question, there is no vtable or vptr in C++, some vendors implement virtual functions using vtables, but its completely implementation dependent.

Arkaitz Jimenez
Although in practive "all" compilers use vtables so I think the question is perfectly legit.
Andreas Brinck
Well, there's the assumption about _the_ vtable. While possible, most compilers can't put all virtual functions in a single table. So many produce multiple vtables for complex types. At that point the real question arises: how the runtime picks the correct one?
MSalters
@MSalters Do you actually know a single compiler that does this, and if so, how *do* they solve this at runtime?
Andreas Brinck
@MSalters Ok, I just thought about it a little bit more and came to the conclusion that is should be possible. You could basically have a "`vtable`" of `vtable`s or something like that.
Andreas Brinck
AFAIK MSVC and GCC both scatter multiple vptr's throughout the object, at different offsets, and adjust object pointers when casted. Pointers to virtual member functions become quite complex in such cases , as you can probably imagine.
MSalters
+1  A: 

The constructor of A will automatically initialize the vtable-pointer to point to the correct vtable. Here's a snippet of the assembly code generated by my compiler for your particular example (this is from A::A):

004114A3  mov         eax,dword ptr [this] 
004114A6  mov         dword ptr [eax],offset A::`vftable' (415740h) 

As you can see the compiler generates code that copies the vftable-pointer for class A to the beginning of the instance.

Andreas Brinck
+1 for pointing out thta this is typically code added to a ctor. What it actually shows is how the vtable _pointer_ is copied to the object. ("offset A::vftable" = offset in memory = pointer)
MSalters
@MSalters Thanks for the catch, I've edited my answer
Andreas Brinck