C++ deleting a derived object via base pointer without a virtual destructor: what sequence prints?\n\n#include <iostream.h>\nclass CuriousTabBase {\npublic:\n CuriousTabBase() { cout << "Base OK. "; }\n ~CuriousTabBase() { cout << "Base DEL. "; }\n};\nclass CuriousTabDerived : public CuriousTabBase {\npublic:\n CuriousTabDerived() { cout << "Derived OK. "; }\n ~CuriousTabDerived() { cout << "Derived DEL. "; }\n};\nint main() {\n CuriousTabBase basePtr = new CuriousTabDerived();\n delete basePtr; // base dtor is non-virtual\n return 0;\n}\n

Difficulty: Medium

Correct Answer: Base OK. Derived OK. Base DEL.

Explanation:


Introduction / Context:
This classic test examines destructor polymorphism. Deleting a derived object through a base pointer whose destructor is not virtual leads to only the base destructor being invoked, which is undefined behavior in standard C++ but typically manifests as the derived destructor not running (a resource leak risk).


Given Data / Assumptions:

  • CuriousTabBase destructor is non-virtual.
  • Object is allocated as CuriousTabDerived but referenced via CuriousTabBase.
  • delete basePtr; is used.


Concept / Approach:
Construction of a derived object prints base message first, then derived message. On deletion through a base pointer without a virtual destructor, only the base destructor is called. The derived destructor is skipped, which is incorrect behavior but matches many legacy outputs.


Step-by-Step Solution:

new CuriousTabDerived() → prints: "Base OK. Derived OK. ".delete basePtr → calls ~CuriousTabBase() only → prints: "Base DEL. ".Combined: Base OK. Derived OK. Base DEL.


Verification / Alternative check:
Making ~CuriousTabBase() virtual would produce: Base OK. Derived OK. Derived DEL. Base DEL.


Why Other Options Are Wrong:

  • Any option including Derived DEL on delete is incorrect without a virtual base destructor.
  • Missing Base DEL omits the observed delete behavior.


Common Pitfalls:
Forgetting to declare virtual destructors in base classes intended for polymorphic deletion; overlooking UB concerns despite predictable prints in many toolchains.


Final Answer:
Base OK. Derived OK. Base DEL.

More Questions from Constructors and Destructors

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion