I didn’t get why we are using the & operator in copy constructor ? what are the problem we are getting if we don’t use it and why?
Copy constructor
What is the difference between
int func(int x)
and
int func(int &x)
In the first function a copy of x is created for local use in the function, whereas in second function a memory reference of variable x is send to function and the function accesses the memory directly.
Now lets try to make a copy constructor:
myClass(myClass a)
In this function, just like we previously established a copy of object ‘a’ will be passed to the copy constructor, but wait, to make a copy of ‘a’, program needs a copy constructor. Deadlock…??
Lets see a roundabout
myClass(myClass &a)
Here the function will be given a memory reference of ‘a’ which obviously exists in the memory and its members will be accessible for initializing members of the new (copy) object.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.