Machine-translated by Google. Questions are authored in English.
Top

Discussion

In C++, what happens if a base class destructor is NOT declared virtual and a derived object is deleted via base pointer ?

  • A.Both base and derived destructors are called
  • B.Only derived class destructor is called
  • C.Compilation error
  • D.Only base class destructor is called

Answer: D

The keyed answer is that only the base class destructor is called.

Deleting a derived object through a base pointer calls the destructor that the pointer's static type selects. If the base destructor is not virtual, there is no dynamic dispatch, so the call goes to the base class destructor and the derived class destructor is skipped, leaking whatever the derived part owned. The C++ standard formally makes this undefined behaviour, but in practice this is what happens, and it is why base classes meant for polymorphic use should have virtual destructors.

Both destructors run, derived first, only when the base destructor is virtual. The derived destructor never runs alone here, and the code compiles without error.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.