Virtual destructor in polymorphic classes

前端 未结 2 1814
一整个雨季
一整个雨季 2021-01-13 19:17

I understand that whenever you have a polymorphic base class, the base class should define a virtual destructor. So that when a base-class pointer to a derived-class object

2条回答
  •  攒了一身酷
    2021-01-13 19:49

    If at the point where you delete the object the static type of the variable is the bas type, than the destructor of the base type will be called, but the destructor of the sub class won't be called (as it is not virtual).

    As a result the resources allocated by the base class will be freed, but the resources allocated by the sub class won't.

    Thus the object won't be destructed correctly.

    You are correct about that table: it is called a virtual method table or "vtable". But the result of the destructor being non-virtual is not that the destructors are not called in the correct order, but that the destructor(s) of the sub class(es) are not called at all!

提交回复
热议问题