Difficulty: Easy
Correct Answer: Reverse order
Explanation:
Introduction / Context:
For robust cleanup, C++ guarantees a predictable destruction order that mirrors construction—reversed. Understanding this is critical when members or resources depend on each other.
Given Data / Assumptions:
Concept / Approach:
Within a single object, base classes are constructed first, then data members in declaration order; destruction happens in the exact reverse: members are destroyed in reverse declaration order, then bases. For multiple objects with automatic storage in a scope, the last constructed is the first destroyed (LIFO), aligning with stack behavior.
Step-by-Step Solution:
1) Construct A then B → destruction runs B then A.2) For a class: Base then Member1 then Member2 → destruction order is Member2 then Member1 then Base.3) This reversal prevents use-after-destruction because dependents go away before their dependencies.4) Therefore, select “Reverse order”.
Verification / Alternative check:
Add logging to constructors and destructors of members and observe the reversed output during teardown.
Why Other Options Are Wrong:
Forward/depends/undefined: conflict with the language's deterministic lifetime rules for contained objects and stack variables.
Common Pitfalls:
Assuming initializer list order controls member construction; it does not—member declaration order does. Destruction still reverses declaration order.
Final Answer:
Reverse order
Discussion & Comments