Possible Duplicate:
Why should the copy constructor accept its parameter by reference in C++?
Can a object be passed as value to the copy constructor
Consider this piece of code:
class complex{
private:
double re, im;
public:
complex(double _re, double _im):re(_re),im(_im){}
complex(complex c):re(c.re),im(c.im){}
};
When compiled, I got an error message: invalid constructor; you probably meant ‘complex (const complex&)’
In the book C++ Programming Language
, it is written that:
The copy constructor defines what copying means – including what copying an argument means – so writing
complex : complex(complex c) :re(c.re) , im(c.im) { } // error
is an error because any call would have involved an infinite recursion.
Why does this cause infinite recursion? It doesn't make sense.
A copy constructor defines what copying means,So if we pass an object only (we will be passing the copy of that object) but to create the copy we will need a copy constructor, Hence it leads to infinite recursion.
In C++ that statement makes a copy of the object's state. In Java it simply copies the reference. The object's state is not copied so implicitly calling the copy constructor makes no sense. And that's all there is to it really.
To copy the values, copy constructor is used. Hence the object being passed and object being used in function are different. Explanation: While returning an object we can use the copy constructor. When we assign the return value to another object of same class then this copy constructor will be used.
Passing by value means that the parameter is copied into the function. That calls the copy constructor.
If your copy constructor parameter is pass-by-value... It would call itself... over and over again...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With