C++ copy constructor parameter: how must a copy constructor receive its argument for correct behavior?

Difficulty: Easy

Correct Answer: only pass-by-reference

Explanation:


Introduction / Context:
A copy constructor’s purpose is to initialize a new object from an existing object of the same type. The parameter type determines whether the constructor is even callable without paradox. This question targets the correct, standard signature style for a copy constructor in C++.


Given Data / Assumptions:

  • We are discussing the canonical copy constructor signature.
  • No vendor extensions; standard C++ rules apply.
  • Best practice includes const correctness.


Concept / Approach:

The copy constructor must take its argument by reference, typically T(const T&). If it were by value, creating the parameter would itself require invoking the copy constructor, creating an infinite regress. Passing by address is not the language-defined copy constructor form and would not be considered a copy constructor by the compiler. Therefore, “only pass-by-reference” is correct, with the conventional form being a const lvalue reference (and a separate move constructor for rvalues in modern C++).


Step-by-Step Solution:

Recognize the signature the compiler treats specially: T(const T&). Reason about by-value parameter: would require another copy → impossible. Address parameter: not treated as a copy constructor by the language. Conclude: only pass-by-reference is valid for a real copy constructor.


Verification / Alternative check:

Compile with T(T) and observe failure or recursion. Replace with T(const T&) and the constructor behaves as expected in copy initialization and direct initialization contexts.


Why Other Options Are Wrong:

Either value or reference: includes an invalid case (by value).

Only by value: impossible for the reasons above.

Only by address: not recognized by the compiler as a copy constructor.


Common Pitfalls:

  • Omitting const, which prevents copying from const objects.
  • Forgetting to also implement or default the move constructor/assignment when needed.


Final Answer:

only pass-by-reference

Discussion & Comments

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