Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 798
Dennis Avatar asked Oct 18 '16 15:10

Dennis


1 Answers

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).

like image 64
Zdeslav Vojkovic Avatar answered Nov 15 '22 11:11

Zdeslav Vojkovic