Copy Constructor vs Assignment Operator in C++
Question
In C++ what is the difference between copy constructor and assignment operator. If they are created for you by default then why do we need to create them in the first place.
Assignment operator vs copy constructor
Copy constructors and assignment operators are created by default even if you do not implement your own. Copy constructors are called whenever an object variable is declared and initialized from another object including the cases when object variable is passed as a function value parameter or when object variable is returned by value from a function.
The difference between copy constructor and assignment operator is that assignment operator is used to copy the values from an object to another already existing object while copy constructor initializes a new object that does not exist before from another object.
We need to implement our own copy constructors and assignment operators simply because default ones do shallow copy or member wise copy which is not enough to clone any object for example if the object contains a pointer to a dynamically allocated memory then shallow copying produces two objects pointing to the same memory. If both objects try to free that memory then this will lead to problems.
If you have any comments, please use the comments section below for questions, corrections or feedback. Thanks for reading.
Nice explanation.
I have a doubt, as you mentioned at the end of the article ‘shallow copy or member wise copy’, can you please tell me which one use shallow copy and which one uses member wise copy (i.e whether copy consturctor or assignment operator uses which type of copy method)..
Default copy constructor and default assignment operator uses shallow copy. Always make sure to redefine them if pointers are used. Redefinition will end up in providing deep copy.