Virtual destructors and deleting objects with multiple inheritance… How does it work?

后端 未结 4 1708
既然无缘
既然无缘 2020-12-14 07:45

First, I understand why virtual destructors are needed in terms of single inheritance and deleting an object through a base pointer. This is specifically about

4条回答
  •  暖寄归人
    2020-12-14 08:24

    The vtable entry simply points at the destructor for AB. It is just defined that after execution of a destructor, the base class destructors are then called:

    After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class X calls [...] the destructors for X’s direct base classes and [...].

    So when the compiler sees delete a; and then sees that the destructor of A is virtual, it looks the destructor up for the dynamic type of a (which is AB) by using the vtable. This finds ~AB and executes it. This results in the calling of ~A and ~B.

    It's not the vtable that says "call ~AB, then ~A, then ~B"; it simply says "call ~AB" which involves calling ~A and ~B.

提交回复
热议问题