C++ object lifecycle: when is a constructor invoked for a class object?
-
AA constructor is called at the time of declaration of an object.
-
BA constructor is called at the time of use of an object.
-
CA constructor is called at the time of declaration of a class.
-
DA constructor is called at the time of use of a class.
Answer
Correct Answer: A constructor is called at the time of declaration of an object.
Explanation
Introduction / Context:Constructors initialize objects to a valid state. Knowing precisely when they run helps you reason about resource acquisition and initialization order, which is critical for RAII patterns in C++ (Resource Acquisition Is Initialization).
Given Data / Assumptions:
- We discuss automatic (stack), static, and dynamic objects (via
new). - “Declaration of an object” is taken to mean its definition/creation.
- We ignore forward declarations without definitions.
Concept / Approach:
Constructors are invoked when an object is created: for automatic objects, upon entering their scope at the definition; for static-duration objects, before main (or on first use for function-local statics with initialization guards); for dynamic objects, immediately when new allocates and constructs. Mere use of an already-constructed object does not call the constructor again. Defining a class type itself does not trigger constructors; only creating instances does.
Step-by-Step Solution:
1) auto T x; ⇒ constructor runs at the point of definition. 2) static T g; ⇒ constructor runs before first use per initialization rules for static storage. 3) T* p = new T(...); ⇒ constructor runs after allocation. 4) Using x later does not call the constructor again; the destructor will run at end-of-life.Verification / Alternative check:
Instrument a constructor with logging and observe when messages print: at creation, not at arbitrary “use” points nor at type declaration time.
Why Other Options Are Wrong:
“time of use of an object”: use does not trigger construction.
“time of declaration/use of a class”: classes are types; only objects have constructors called.
Common Pitfalls:
- Confusing declaration with forward declaration; only definitions create objects.
- Assuming copy elision rules always call or skip constructors—modern C++ may elide but construction still conceptually occurs.
Final Answer:
A constructor is called at the time of declaration of an object.