Search code examples
c++copy-constructorcopy-assignment

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?


Solution

  • 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?