Search code examples
c++destructionvptr

Does the vptr change during destruction?


I was looking at this article, and it says "Upon entry to the base class destructor, the object becomes a base class object, and all parts of C++—virtual functions, dynamic_casts, etc.—treat it that way." Does this mean that the vptr has changed during destruction? How does that happen?


Solution

  • In all implementations that use virtual function tables (i.e. all current C++ implementations) the answer is yes, the vptr changes to that of the type of the destructor that is being executed. The reason is that the standard requires that the type of the object being destructed is the type of the destructor being exectued.

    If you have a hierarchy of three types B, D, MD (base, derived, most derived) and you instantiate and destroy an object of type MD, then while executing MD::~MD() the type of the object is MD, but when the implicit call to the base destructor is executed, the runtime type of the object must be D. This is achieved by updating the vptr.