Vptr doubt - need to know how it gets the Vtable address

I wanted to know how vptr gets the base address of vtable.

eg

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

Now,

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

I wanted to know this secret. thanks in advance

+3
source share
4 answers

vptr is initialized by code generated by the compiler as part of the initialization obj. There is no magic, he just assigns it like this:

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 fake code showing how the compiler can implement vptr. I have no idea which particular code compilers are spitting out these days.

+1
source

This is not a question in C ++, in C ++ there is no vtable or vptr, some manufacturers implement virtual functions using vtables, but they are completely implementation dependent.

+1

A vtable-, vtable. , ( A::A):

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

, , vftable-pointer A .

+1

vtable , vtable . , , vptr Vtable.

0

Source: https://habr.com/ru/post/1746545/


All Articles