Copy constructor is needed if we defined parametric constructor with deep copy? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Copy constructor is needed if we defined parametric constructor with deep copy?

Hi Refer code: https://code.sololearn.com/cbS0Ob06MPhM I have a class having data member as char* and hence I allocated memory based on input data into parameterized constructor. Do I need to have deep copy into copy constructor? Shallow copy provided by compiler also work and changing obj1 by doing setName is not causing change of obj2. Can I say now in this code deep copy constructor is not needed or am I missing something?

20th Jan 2022, 5:43 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Answers
+ 1
You're allocating memory from the heap for one of your member variables which means you have to delete it at some point. If you do a shallow copy you'll end up deleting the same memory twice in the destructor. So yes, this class needs to deep copy its heap allocated variable. The only reason it's working is because you're not calling delete in the destructor and because setName changes the pointer to not point to the heap anymore. You will also need a copy/move assignment operator. https://cpppatterns.com/patterns/rule-of-five.html
20th Jan 2022, 10:05 PM
Dennis
Dennis - avatar
+ 1
Yep, this code looks fine to me, it's doing the deep copying correctly. There are of course some changes I would make to remove some of the code duplication and to use cstring instead of string.h, but I assume it's just sample code.
21st Jan 2022, 12:24 PM
Dennis
Dennis - avatar
0
Thank you so much. I created new code with above changes. https://code.sololearn.com/c62Nmw7aV8w4 If time permits, can you or anyone suggest any feedback on same?
21st Jan 2022, 11:52 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Yup... Dennis thank you so much...
21st Jan 2022, 12:55 PM
Ketan Lalcheta
Ketan Lalcheta - avatar