Possible Duplicate:
Why should the copy constructor accept its 开发者_StackOverflow中文版parameter by reference in C++?
why do we have have a reference always in a copy constructor?
if there is a class
:
class Base{};
its copy constructor is:
Base::Base(const Base& B);
why is always a reference as the argument?
Had it not been a reference, the compiler would need to invoke the copy constructor in order to pass the parameter to the copy constructor.
That would result in a
(source: prodeveloper.org)
.
If you tried to pass the parameter by value the compiler would have to copy the parameter and that would again invoke the copy constructor. This would lead to endless recursion and stack overflow.
copy-constructor is called when there is a need of making a copy of your object.
Now think, if the copy-constructor doesn't take reference of the object, that means you've to pass it by value that in turn would require making a copy of your original object. That means, it'll again call copy-constructor, to make a copy of the object. In this way, it'll keep on calling copy-constructor.
精彩评论