Order of destruction in C++: destructor calls occur in what relation to the order of the corresponding constructor calls?

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:

  • An object aggregates subobjects (members, bases).
  • Construction occurs in a fixed order; we seek the destruction order.
  • Stack objects within a block are constructed in sequence and destroyed in reverse sequence.

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

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