Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should the copy constructor accept its parameter by reference in C++?

Why must a copy constructor's parameter be passed by reference?

like image 279
Jony Avatar asked Oct 06 '22 17:10

Jony


2 Answers

Because if it's not by reference, it's by value. To do that you make a copy, and to do that you call the copy constructor. But to do that, we need to make a new value, so we call the copy constructor, and so on...

(You would have infinite recursion because "to make a copy, you need to make a copy".)

like image 211
GManNickG Avatar answered Oct 19 '22 21:10

GManNickG


Because pass-by-value would invoke the copy constructor :)

like image 73
Brian Roach Avatar answered Oct 19 '22 19:10

Brian Roach