Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not only one? Copy constructor and assignment operator

I understand which is invoked in what situation...

Sample a;
Sample b = a; //calls copy constructor
Sample c;
c = a;        //calls assignment operator

My question is Why these 2 different things exist at all? Why can't only one of the two take care of both situations?

like image 369
NightFurry Avatar asked Jul 16 '14 10:07

NightFurry


People also ask

Why copy constructor and assignment operator's working is different?

The difference between a copy constructor and an assignment operator is that a copy constructor helps to create a copy of an already existing object without altering the original value of the created object, whereas an assignment operator helps to assign a new value to a data member or an object in the program.

Why a class should have both a copy constructor and an overloaded assignment operator?

Both the copy constructors and assignment operators copies from one object to another then why do we need both? Copyconstructor means it creates a new object and copies the contents from another exist object and assignment operator copies the contents from one existing object to the already existing object.

Can you use the copy constructor in the assignment operator?

You can safely invoke the copy assignment operator from the constructor as long as the operator is not declared virtual.

Is there any situation where you want to only implement a copy constructor or an assignment operator but not both?

No, they are different. Copy constructor is used for constructing a new object (from another object). In this case you just need to initialize the members. Assignment operator is used for an existing object (you may have constructed it by default constructor etc), and then assign it by another object.


1 Answers

No, they are different.

Copy constructor is used for constructing a new object (from another object). In this case you just need to initialize the members.

Assignment operator is used for an existing object (you may have constructed it by default constructor etc), and then assign it by another object. In this case you need to re-initialize members, sometimes means destroying and initializing them again.

Even so, the functionality of them are so similar, so you can share their implementation usually. Such as: What is the copy-and-swap idiom?

like image 84
songyuanyao Avatar answered Nov 15 '22 05:11

songyuanyao