Search code examples
c++performancememory-layoutcompiler-constructionvptr

Why is vptr stored as the first entry in the memory of a class with virtual functions?


For some compilers, if a class has virtual functions then its vptr can be accessed with the address of the first byte of its object. For instance,

class Base{
public:
    virtual void f(){cout<<"f()"<<endl;};
    virtual void g(){cout<<"g()"<<endl;};
    virtual void h(){cout<<"h()"<<endl;};
};

int main()
{   
   Base b;

   cout<<"Address of vtbl:"<<(int *)(&b)<<endl;

   return 0;
}

I know that it is dependent on different compiler behaviors. Since there is the case where vptr is stored as the very first entry, what is the advantage of doing this? Does that help improve performance or simply because it's easier to access vbtl using &b?


Solution

  • It's an implementation detail but indeed many implementations do this.

    It's rather efficient and convenient. Suppose you need to call a virtual function for a given object. You have a pointer to that object and the virtual function index. You need to somehow find which function should be called with that index and for this object. Okay, you simply access the first sizeof(void*) bytes behind the pointer and find where the vtable resides, then access the necessary element of vtable to fetch the function address.

    You could store a separate map of "vtable for each object" or something but if you decide that you want to store the vptr inside the object then it's only logical to use the first bytes, not the last bytes or any other place because with this approach you know where to find the vptr once you have a pointer to the object, no extra data required.