Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is copy constructor not allowed pass by value? [duplicate]

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.

like image 814
Amumu Avatar asked Dec 08 '11 19:12

Amumu


People also ask

Why can not we pass an object by value to a copy constructor I had explained why it will go to infinite loop then written code to demonstrate that?

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.

Why copy constructor is not used in Java?

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.

What type of variables we can pass to copy constructor?

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.


1 Answers

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...

like image 61
Mysticial Avatar answered Sep 18 '22 18:09

Mysticial