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.

Copy Constructor vs Assignment Operator in C++

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.

Tags:
2 Comments

Add a Comment

Your email address will not be published. Required fields are marked *