gobi
gobi

Reputation: 31

Doubt in Vptr -want to know how it is getting Vtable address

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

Upvotes: 3

Views: 594

Answers (4)

Jiguan
Jiguan

Reputation: 1

The compiler generate the vtable of one class,and the address of vtable is determined when compiling.So if you instance an object at runtime,the vptr obtains the address of Vtable.

Upvotes: 0

Andreas Brinck
Andreas Brinck

Reputation: 52549

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.

Upvotes: 1

Marcelo Cantos
Marcelo Cantos

Reputation: 185962

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.

Upvotes: 1

Arkaitz Jimenez
Arkaitz Jimenez

Reputation: 23198

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.

Upvotes: 1

Related Questions