I know that C++ compiler creates a copy constructor for a class. In which case do we have to write a user-defined copy constructor? Can you give some examples?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The copy constructor generated by the compiler does member-wise copying. Sometimes that is not sufficient. For example:
in this case member-wise copying of
storedmember will not duplicate the buffer (only the pointer will be copied), so the first to be destroyed copy sharing the buffer will calldelete[]successfully and the second will run into undefined behavior. You need deep copying copy constructor (and assignment operator as well).