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:
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:
Common Pitfalls:Forgetting that the inner object is destroyed before the outer objects, and that destructors run in reverse construction order.
Final Answer:12344321
Discussion & Comments