• Advertisement
Sign in to follow this  

Copy Constructor

This topic is 2383 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Why the argument of a Copy constructor is passed by reference? What would happen if it is passed by Value?

Share this post


Link to post
Share on other sites
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);
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement