C++ object lifetime: how many times is a constructor invoked during the entire lifetime of a single object? Choose the most accurate statement.
-
AOnly once
-
BTwice
-
CThrice
-
DDepends on the way of creation of object
Answer
Correct Answer: Only once
Explanation
Introduction / Context:Constructors in C++ are special member functions that initialize an object into a valid state. Understanding exactly how many times a constructor is called per object helps clarify object lifetime, copy/move semantics, and where initialization truly happens versus later mutations.
Given Data / Assumptions:
- We are talking about a single, concrete object instance.
- Object creation may be automatic (block scope), dynamic (using new), static, or temporary.
- Copy and move constructors count as constructors too, but each applies only when a new object is created.
Concept / Approach:
A constructor (of some form) is called exactly once for each object: at its creation. After the object exists, later assignments or method calls do not “reconstruct” it; they simply modify state. If an object is created via copy or move, the corresponding copy/move constructor is the one invoked, still exactly once for that object. Reassignment later invokes assignment operators, not constructors.
Step-by-Step Solution:
For an automatic object T x; → one constructor call at definition. For a dynamically allocated object new T(...) → one constructor call at allocation site. For a copy T y = x; → one copy constructor call for y (still once per y). For a temporary T() → one constructor call for that temporary instance.Verification / Alternative check:
Add logging to all constructors and operators. You will observe exactly one constructor log per created object, matched by at most one destructor log at end-of-life (if not elided). Copy elision can remove extra temporary constructions, but each ultimately created object is still constructed once.
Why Other Options Are Wrong:
Twice/Thrice: there is no scenario where a single object is “constructed” multiple times.
Depends on the way of creation: the specific constructor overload may differ, but the count per object remains one.
Common Pitfalls:
- Confusing copy assignment with copy construction; only the latter creates a new object.
- Misreading logs when copy elision/moves are at play.
Final Answer:
Only once