开发者

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

开发者 https://www.devze.com 2022-12-30 22:34 出处:网络
i wanted to kno开发者_StackOverfloww how vptr getting vtable base address. for instance class A { virtual getdata();

i wanted to kno开发者_StackOverfloww 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


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消