C++ object lifetime for automatic objects: constructors and destructors are called when objects…

Difficulty: Easy

Correct Answer: enter and leave scope

Explanation:


Introduction / Context:
Automatic (stack-allocated) objects in C++ embody RAII: they acquire resources on creation and release them automatically when leaving scope. Knowing precisely when constructors and destructors run enables predictable resource management without manual calls to free or close APIs.


Given Data / Assumptions:

  • “Automatic objects” means block-scope variables with automatic storage duration.
  • We are focusing on scope entry/exit behavior.
  • Not considering static storage or dynamic allocation via new/delete here.


Concept / Approach:

When execution enters the scope where an automatic object is defined, its constructor runs at the point of definition. When execution leaves that scope (normally or via exceptions), the object’s destructor runs automatically, in reverse order of construction for multiple objects. This is the core of exception-safe cleanup and deterministic finalization in C++.


Step-by-Step Solution:

At scope entry and object definition ⇒ constructor runs. At scope exit (including stack unwinding due to exceptions) ⇒ destructor runs. This pairing ensures resources are released even on early returns or exceptions. Therefore, “enter and leave scope” best captures both calls succinctly.


Verification / Alternative check:

Instrument a class with logging in constructor and destructor. Observe creation when the variable is defined and destruction when the enclosing block is left, regardless of the exit path.


Why Other Options Are Wrong:

“inherit parent class” — unrelated to lifetime events.

“are constructed” or “are destroyed” — each covers only one side of the lifecycle, not both.


Common Pitfalls:

  • Assuming destructors run at program end only; for automatic objects they run at scope exit.
  • Forgetting that static and dynamic objects have different timing rules.


Final Answer:

enter and leave scope

Discussion & Comments

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