Discussion
In C++, what happens if a base class destructor is NOT declared virtual and a derived object is deleted via base pointer ?
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.
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development