C++ – When exactly does the virtual table pointer (in C++) gets set for an object

cconstructorvirtual-functionsvptrvtable

I know that for any class that has a virtual function or a class that is derived from a class that has a virtual function, the compiler does two things. First, it creates a virtual table for that class and secondly, it puts a virtual pointer (vptr) in the base portion for the object. During runtime, this vptr gets assigned and starts pointing to the correct vtable when the object gets instantiated.

My question is that where exactly in the instantiation process does this vptr gets set? Does this assignment of vptr happens inside the constructor of the object of before/after the constructor?

Best Answer

This is strictly Implementation dependent.

For Most compilers,

The compiler initializes this->__vptr within each constructor's Member Initializer list.

The idea is to cause each object's v-pointer to point at its class's v-table, and the compiler generates the hidden code for this and adds it to the constructor code. Something like:

Base::Base(...arbitrary params...)
   : __vptr(&Base::__vtable[0])  ← supplied by the compiler, hidden from the programmer
 {

 }

This C++ FAQ explains a gist of what exactly happens.

Related Topic