I read here that if I don't write a copy constructor the compiler does it for me using the assignment operator, which results in shallow copy of Objects. What if I do have the assignment operator overloaded in all of my member object? wouldn't it result in a deep copy?
3 Answers
if I don't write a copy constructor the compiler does it for me using the assignment operator
No, it doesn't use the assignment operator; it does it via a implicitly generated copy constructor which does a shallow copy.
What if I do have the assignment operator overloaded in all of my member object? wouldn't it result in a deep copy?
Given that the assignment operator is not used in absence of explicitly defined copy constructor, even though you have the assignment operator overloaded you still need to overload the copy constructor as well.
Read the Rule of Three in C++03 & Rule of Five in C++11.
5 Comments
char * in a vector. Now how do I write the destructor." etc. Point is, with well composed class design, writing any of the Big 3/5 should be a rare, localised occurrence.You're misinformed. The implicitly generated constructors and assignment operators simply perform construction or assignment recursively on all members and subobjects:
copy constructor copies element by element
move constructor moves element by element
copy assignment assigns element by element
move assign move-assigns element by element
This logic is the reason why the best design is one in which you don't write any copy constructor (or any of the other three, or the destructor) yourself, and instead compose your class of well-chosen, single-responsibility classes whose own semantics take care of everything.