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?
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
.
Derived
vptr for virtual functions that don't appear in Base
. But the per-object overhead is not so nice. –
Arnhem Yes it is completely implementation dependent.
For a simple inheritance hierarchy it is located at the beginning of the object but for a complex hierarchy it won't be.
Anyhow, any source code you write should not rely on where it is located, in fact any code you write should not rely on even existence of a virtual table or a virtual table pointer.
The C++ Standard does not mandate that virtual dispatch be implemented through virtual table and pointer, an implementation is free to implement it using an other implementation method, However all mainstream compilers do implement this through table pointer mechanism the important point to note is they may differ in exact implementation of where the pointer is located etc.
© 2022 - 2024 — McMap. All rights reserved.