Copy Constructor

Started by
2 comments, last by Telgin 12 years, 8 months ago
Why the argument of a Copy constructor is passed by reference? What would happen if it is passed by Value?
Advertisement
It'd be like dividing by zero: It'll explod the entire Universe!!!`11!`!!!eleven


class Fred {
public:
Fred() {
}

Fred( Fred temporary ) {
}
};

int main() {
Fred fred1;

// In order to copy-construct fred2 from fred1, we will pass fred1 into fred's copy-constructor.
// To pass an object by value requires that we copy-construct a new fred from fred1.
// However, in order to copy-struct a new fred from fred1 by value, we need another fred ...
// And so on ...
Fred fred2(fred1);
}
Passing by value is better choice in some circumstances. Want Speed? Pass by Value.

Passing by value is better choice in some circumstances. Want Speed? Pass by Value.


But not in copy constructors.
As fastcall22 put rather humorously, there is no way to resolve a copy constructor with the object passed by value.

The reason is that the copy constructor would need to already exist for this to work. The whole purpose of the copy constructor is to create a copy of an object when it's needed. Any time you assign by value, you are invoking the copy constructor, and by passing in by value to a copy constructor, you'd need the copy constructor, which would then need the copy constructor, and so on. In this case it's not a question of efficiency, so much as it's the only way to do it.
Success requires no explanation. Failure allows none.

This topic is closed to new replies.

Advertisement