Advantage of user defined copy constructor over default copy constructor
Answers
Explanation:
The default copy constructor is generated by the compiler when one is not declared. The implementation makes a member-wise copy (a shallow copy) of the class members. For many classes this is adequate.
The default copy constructor is generated by the compiler when one is not declared. The implementation makes a member-wise copy (a shallow copy) of the class members. For many classes this is adequate.However, if your class contains pointer member variables and the memory they point to is allocated within the class itself, then those pointers must be deep copied. If they are shallow copied, then you will end up with two separate instances of the class pointing at the same memory. Thus when one instance is destroyed, the other is immediately invalidated. Deep copying ensures both instances point to their own memory allocations. To perform a deep copy you must include a user-defined copy constructor. You will also have to perform a member-wise copy of all the non-pointer member variables.
Answer:
The default copy constructor is generated by the compiler when one is not declared. The implementation makes a member-wise copy (a shallow copy) of the class members. For many classes this is adequate.
The default copy constructor is generated by the compiler when one is not declared. The implementation makes a member-wise copy (a shallow copy) of the class members. For many classes this is adequate.However, if your class contains pointer member variables and the memory they point to is allocated within the class itself, then those pointers must be deep copied. If they are shallow copied, then you will end up with two separate instances of the class pointing at the same memory. Thus when one instance is destroyed, the other is immediately invalidated. Deep copying ensures both instances point to their own memory allocations. To perform a deep copy you must include a user-defined copy constructor. You will also have to perform a member-wise copy of all the non-pointer member variables.
within the class itself, then those pointers must be deep copied. If they are shallow copied, then you will end up with two separate instances of the class pointing at the same memory. Thus when one instance is destroyed, the other is immediately invalidated. Deep copying ensures both instances point to their own memory allocations. To perform a deep copy you must include a user-defined copy constructor. You will also have to perform a member-wise copy of all the non-pointer member variables.Note that if pointers are allocated memory outside of the class (the memory doesn't belong to the class), a shallow copy is fine. However, the onus is upon you, the programmer, to ensure the allocated memory remains in a valid state during the entire life-cycle of all the class instances pointing at the same memory.