C++ (constructor/destructor order) — determine the exact output produced by construction of multiple objects and their destruction including a nested scope.\n\n#include<iostream.h>\nint val = 0;\nclass CuriousTab {\npublic:\n CuriousTab() { cout << ++val; }\n ~CuriousTab() { cout << val--; }\n};\nint main() {\n CuriousTab objCuriousTab1, objCuriousTab2, objCuriousTab3;\n { CuriousTab objCuriousTab4; }\n return 0;\n}\n\nWhat character sequence is written to stdout?

Difficulty: Medium

Correct Answer: 12344321

Explanation:


Introduction / Context:
This program tests your understanding of C++ object lifetime: when constructors run, when destructors run, and the order they print values when a global counter is incremented/decremented. It also includes a temporary object in a nested block to verify scope-bound destruction.


Given Data / Assumptions:

  • Global int val starts at 0.
  • Constructor prints ++val (pre-increment then print).
  • Destructor prints val-- (print current val then post-decrement).
  • Three automatic objects in main scope; one additional automatic object in an inner block.


Concept / Approach:
Automatic objects are constructed in declaration order and destroyed in reverse order of construction when their scope ends. An object created inside an inner block is destroyed at the end of that block, before the outer-scope objects are destroyed.


Step-by-Step Solution:

1) Construct obj1 → ++val: 1 → prints 1.2) Construct obj2 → ++val: 2 → prints 2.3) Construct obj3 → ++val: 3 → prints 3.4) Enter inner block; construct obj4 → ++val: 4 → prints 4.5) End inner block; destroy obj4 → prints current val 4, then val becomes 3.6) End of main scope: destroy obj3 → prints 3 (val becomes 2), then obj2 → prints 2 (val becomes 1), then obj1 → prints 1 (val becomes 0).


Verification / Alternative check:
Trace val on paper to ensure increments and decrements line up with construction/destruction order.


Why Other Options Are Wrong:

  • 1234 / 4321: Ignore destructors or construction order.
  • 12341234 / 43211234: Misorder destruction or duplicate patterns.


Common Pitfalls:
Forgetting that the inner object is destroyed before the outer objects, and that destructors run in reverse construction order.


Final Answer:
12344321

More Questions from Constructors and Destructors

Discussion & Comments

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