C++ virtual destructor behavior (legacy iostream.h): when deleting via a base-class pointer, in what order do constructor and destructor messages appear? #include<iostream.h> class CuriousTabBase{ public: CuriousTabBase(){ cout << "Base OK. "; } virtual ~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; }

Difficulty: Easy

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

Explanation:

Introduction / Context:This question checks understanding of polymorphic destruction in C++. If a base class has a virtual destructor, deleting through a base pointer calls the most-derived destructor first, then unwinds to the base.

Given Data / Assumptions:

  • Constructors print: Base OK. then Derived OK.
  • Destructors print: derived then base when invoked virtually.
  • Deletion occurs via CuriousTabBase.

Concept / Approach:A virtual base destructor ensures correct dynamic dispatch on delete basePtr. Construction order is base→derived; destruction order is reverse: derived→base.

Step-by-Step Solution:1) Construction prints: Base OK. (base ctor) then Derived OK. (derived ctor).2) Deletion through base pointer with virtual dtor: calls ~CuriousTabDerived → prints Derived DEL.3) Then calls ~CuriousTabBase → prints Base DEL.

Verification / Alternative check:Remove virtual and you'll observe only base destructor runs via the base pointer (resource leak risk).

Why Other Options Are Wrong:They either omit one of the destructor messages or present the non-virtual deletion order.

Common Pitfalls:Forgetting to mark base destructors virtual when using polymorphism leads to undefined behavior or leaks.

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

More Questions from Constructors and Destructors

Discussion & Comments

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