Question:

What is difference between shallow copy and deep copy? Which is default?

Answer:

[This question can be expected in any interviews, not just c++ interviews. This is a usual question in most of the java interviews.]

When you do a shallow copy, all the fields of the source object is copied to target object as it is. That means, if there is a dynamically created field in the source object, shallow copy will copy the same pointer to target object. So you will have two objects with fields that are pointing to same memory location which is not what you usually want.
In case of deep copy, instead of copying the pointer, the object itself is copied to target. In this case if you modify the target object, it will not affect the source. By default copy constructors and assignment operators do shallow copy. To make it as deep copy, you need to create a custom copy constructor and override assignment operator.


Keywords:

© 2017 QuizBucket.org