Skip to main content

Reference argument in copy constructor

Short answer

The copy constructor's parameter must be a reference to avoid infinite recursion. Passing by value would require copying the argument using the copy constructor itself, leading to endless calls. A reference also avoids an extra copy, improving efficiency.

Why do you need a reference in the argument to the copy constructor?

A copy constructor has the form ClassName(ClassName &obj) or ClassName(const ClassName &obj). The argument must be passed by reference, not by value.

Reason: infinite recursion

If the parameter were by value, ClassName(ClassName obj):

  1. To call the copy constructor, the argument must first be copied into the parameter obj.
  2. Copying the argument into obj needs the copy constructor itself to be called.
  3. That call again needs a copy for its own parameter, and so on without end.

This is endless recursion, so the compiler rejects it (error: invalid constructor, argument must be passed by reference).

A b = a;  -> copy ctor(A obj = a)
              -> needs copy ctor to build obj
                  -> needs copy ctor ... (infinite)

Other benefits of a reference

  • No temporary copy is made, so it is faster and uses less memory.
  • It refers to the original object, so the data of the source is read directly.
  • Using const prevents the source object from being modified accidentally, and allows copying from const objects and temporaries.
class Point
{
    int x, y;
public:
    Point(int a, int b) { x = a; y = b; }
    Point(const Point &p) { x = p.x; y = p.y; }   // reference argument
};
Point p1(2, 3);
Point p2 = p1;     // calls copy constructor

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 4 questions →