- 2073 Shrawan · 3 marks
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):
- To call the copy constructor, the argument must first be copied into the parameter
obj. - Copying the argument into
objneeds the copy constructor itself to be called. - 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
constprevents 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)
Related questions
- Constructors: need and types · Object Oriented Programming, chapter 4 · asked 2×
- Field books and reference sketch · Surveying I, chapter 3 · asked 2×
- Need of formulation; techniques for ToR · Project Engineering, chapter 2
- Human need and Herzberg's hygiene theory · Organization and Management, chapter 8 · asked 2×
- Election algorithm need and example · Distributed System, chapter 6 · asked 2×