- #1
yungman
- 5,755
- 293
In operator overload I often see the parameter is always a reference parameter. I want to find out why. I read the Copy Constructor in the book. I want to verify whether I understand this correctly as it's really important. I use "xx" just to represent some operator like =, >> etc.
This is the copy of the two pages in the book explaining why and I had to read it quite a few times to understand it. I still want to verify here:
The way I understand it, if I write it like this
, the operator function will first make a copy of the object of the RIGHT side of the xx and call it obj. But then when obj is first created, it will call the Copy Constructor and create another copy of obj(say called obj2), then when obj2 is created, it will call the Copy Constructor again and create another obj( called obj3) and it will keep doing it over and over until it bombed.
That's the reason it has to pass by reference so NO copy is created and no Copy Constructor will be called at this point.
This is the pdf of the Gaddis book, it's in Page 818 - 819:https://cplusplushelp.weebly.com/uploads/2/5/6/5/25655197/0136022537.pdf
Thanks
C++:
class ABC;
void operator xx (ABC & obj);
This is the copy of the two pages in the book explaining why and I had to read it quite a few times to understand it. I still want to verify here:
C++:
void ABC xx (ABC obj)
That's the reason it has to pass by reference so NO copy is created and no Copy Constructor will be called at this point.
This is the pdf of the Gaddis book, it's in Page 818 - 819:https://cplusplushelp.weebly.com/uploads/2/5/6/5/25655197/0136022537.pdf
Thanks