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?
As I understand, the location of the virtual function pointer table in an object
Share
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:
If the vptr was stored at the end of the object, then it would be after
sizeof(T)bytes for an object of complete typebase. Now when you have an object of complete typederived, the layout of thebasesub object must be compatible with the layout of a completebaseobject, so thevptrwould still have to besizeof(T)bytes inside the object, which would be somewhere in the middle of thederivedobject (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
thispointer, a virtual call requires an indirection through the vtable, which basically is dereferencing thevptr, adding an offset and jumping to the memory location stored there. If thevptrwas stored at the end of the object, for each virtual call there would be an extra addition tothisbefore dereferencing thevptr.