Search code examples
c++oopvirtual-functionsvptr

location of virtual function table pointer in object


As I understand, the location of the virtual function pointer table in an object is compiler dependent.
Are there any pros/cons of placing this pointer at the beginning of the object vs at the end or vice-versa?


Solution

  • The mere existence of a virtual function table is compiler dependent (but all compilers do), and the location is not mandated either... In all compilers of which I know the details, the vptr is stored in the beginning of the object. The reason is that it provides a uniform location. Consider a class hierarchy:

    struct base {
       T data;
       virtual void f();
    };
    struct derived : base {
       T1 data;
       virtual void g();
    };
    

    If the vptr was stored at the end of the object, then it would be after sizeof(T) bytes for an object of complete type base. Now when you have an object of complete type derived, the layout of the base sub object must be compatible with the layout of a complete base object, so the vptr would still have to be sizeof(T) bytes inside the object, which would be somewhere in the middle of the derived object (sizeof(T) from the beginning, sizeof(T1) before the end). So it would no longer be at the end of the object.

    Additionally, given a this pointer, a virtual call requires an indirection through the vtable, which basically is dereferencing the vptr, adding an offset and jumping to the memory location stored there. If the vptr was stored at the end of the object, for each virtual call there would be an extra addition to this before dereferencing the vptr.