C++ deleting a derived object via base pointer without a virtual destructor: what sequence prints?
#include
class CuriousTabBase {
public:
CuriousTabBase() { cout << "Base OK. "; }
~CuriousTabBase() { cout << "Base DEL. "; }
};
class CuriousTabDerived : public CuriousTabBase {
public:
CuriousTabDerived() { cout << "Derived OK. "; }
~CuriousTabDerived() { cout << "Derived DEL. "; }
};
int main() {
CuriousTabBase basePtr = new CuriousTabDerived();
delete basePtr; // base dtor is non-virtual
return 0;
}
-
ABase OK. Derived OK.
-
BBase OK. Derived OK. Base DEL.
-
CBase OK. Derived OK. Derived DEL.
-
DBase OK. Derived OK. Derived DEL. Base DEL.
-
EBase OK. Derived OK. Base DEL. Derived DEL.
Answer
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.