C++ object lifecycle: a constructor is executed when which of the following events occurs?

Difficulty: Easy

Correct Answer: an object is created

Explanation:


Introduction / Context:
Constructors are special member functions that initialize objects. Understanding exactly when they run is essential to reason about resource acquisition, invariants, and performance. This question focuses on the trigger for constructor execution in C++ programs across different storage durations (automatic, static, dynamic, and temporary objects).


Given Data / Assumptions:

  • Constructors exist in multiple forms: default, parameterized, copy, and move.
  • Each object is constructed exactly once at creation.
  • Destructors, not constructors, run when objects leave scope or are deleted.


Concept / Approach:

The act of creating an object—defining it, allocating it dynamically, or forming a temporary—invokes a suitable constructor. Using an existing object does not “reconstruct” it. Declaring a class type by itself does not run a constructor because no instance exists. At scope exit, the destructor runs to clean up.


Step-by-Step Solution:

Define T x; → constructor runs at definition point. Invoke new T(args); → storage is allocated, then constructor runs. Create temporary T() or return-by-value → constructor (or elision) applies. At scope exit or delete, the destructor (not constructor) runs.


Verification / Alternative check:

Add logging in constructors and destructors. Observe the constructor messages at creation and destructor messages at scope exit/deletion, confirming the lifecycle order.


Why Other Options Are Wrong:

“An object is used” does not construct anything; the object already exists.

“A class is declared” introduces a type but no instance; no construction occurs.

“An object goes out of scope” triggers the destructor, not the constructor.


Common Pitfalls:

  • Confusing copy assignment with copy construction.
  • Expecting virtual dispatch to fully work inside constructors (dynamic type not complete yet).


Final Answer:

an object is created

More Questions from Objects and Classes

Discussion & Comments

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