Dennis Dennis - 1 year ago 67
C++ Question

Is it safe for a C++ base class to store the value of 'this' for future virtual calls after construction?

In C++ in a Base constructor, the actual type of 'this' is 'Base' not 'Derived', so it's unsafe to call virtual functions. However, is it safe for the base class to pass the value of 'this' during base construction to a callback object that will call a virtual function at a future time after construction is complete?

Answer Source

In constructor it is not unsafe to call virtual methods because of this being of type Base but because the object is not fully constructed yet. Derived members are not initialized at this point, so executing the virtual method implementation in Derived would operate on uninitialized instances.

This is why standard specifies that during constructor/destructor call the function called is the final overrider in the constructor’s or destructor’s class and not one overriding it in a more-derived class

You can safely store it and call virtual functions on it from the moment it is fully constructed, i.e. right after the constructor exits (those virtual functions which are defined on Base class, of course).