C++ (constructor/destructor calls and manual destructor invocation) — what is printed when explicitly calling a destructor on an automatic object?\n\n#include<iostream.h>\nclass CuriousTabBase { public: CuriousTabBase(){ cout << "Base OK. "; } };\nclass CuriousTabDerived: public CuriousTabBase {\npublic:\n CuriousTabDerived(){ cout << "Derived OK. "; }\n ~CuriousTabDerived(){ cout << "Derived DEL. "; }\n};\nint main(){\n CuriousTabBase objB; // base object\n CuriousTabDerived objD; // derived object\n objD.~CuriousTabDerived(); // explicit destructor call (dangerous)\n return 0;\n}\n\nChoose the observed output.

Difficulty: Medium

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

Explanation:


Introduction / Context:
This program demonstrates construction order for base/derived classes and the consequences of explicitly calling a destructor on an object with automatic storage. While legal to call, doing so leads to the destructor being invoked twice, which is undefined behavior. The question focuses on the typical printed sequence seen in many environments.


Given Data / Assumptions:

  • objB (base) prints "Base OK. " during its construction.
  • objD (derived) first constructs its base subobject ("Base OK. "), then its own constructor ("Derived OK. ").
  • Explicit call objD.~CuriousTabDerived() prints "Derived DEL. " once.


Concept / Approach:
Automatic objects are destroyed at scope end. Manually calling the destructor does not change that; the compiler will still call the destructor again when the object goes out of scope. Although the behavior is undefined, the commonly observed effect is two destructor prints for objD.


Step-by-Step Solution:

1) Construct objB → "Base OK. ".2) Construct objD → base: "Base OK. ", then derived: "Derived OK. ".3) Manual destructor call → "Derived DEL. ".4) End of main → destructor called again for objD → "Derived DEL. " (UB but typical), then objB is destroyed silently (no message).


Verification / Alternative check:
Remove the explicit call; you will see a single "Derived DEL. " at scope exit.


Why Other Options Are Wrong:

  • Options lacking the first "Base OK. " miss objB construction.
  • Single DEL reflects the safe case without manual call.


Common Pitfalls:
Calling destructors directly on automatic objects; instead, let scope end manage destruction.


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

More Questions from Constructors and Destructors

Discussion & Comments

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