0

How to create copy constructor in a class with an array

Hi guys I'm still a noob coder and I need some help with an exercise. Given the class MyString (see code below) how can I create copy constructor, destructor and assignment operator? I know that since the class contains dynamic allocated memory the default copy constructor, default destructor and default assignment operator don't work well. I have trouble finding the right solution to implement the class... https://code.sololearn.com/cPGhVjx30ZJc/?ref=app

12th Jul 2019, 9:02 AM
Frangiax
Frangiax - avatar
9 odpowiedzi
+ 2
In the destructor, you will want to free the allocated memory, just the way you wrote it. For the copy constructor, you basically call the normal constructor with the size of the string you want to copy, and afterwards you simply copy every character using a for-loop. Same for the assignment operator, although here you need to free the memory first before allocating a new string. Another way would be to simply use swap() from the <utility> library. An implementation could look like this: https://code.sololearn.com/c9uyVP6jfpPw/?ref=app
12th Jul 2019, 9:22 AM
Shadow
Shadow - avatar
+ 1
Thank you guys so much! Fasten your seat belts for another dumb question regarding the copy constructor: is it okay if I pass as a parameter (const MyString & name) instead of (MyString const & name)?
12th Jul 2019, 9:57 AM
Frangiax
Frangiax - avatar
+ 1
Thank you! You're my lifesavers! Have a great day
12th Jul 2019, 10:09 AM
Frangiax
Frangiax - avatar
+ 1
It's me again! I've been working on another exercise which was pretty much the same thing as the one previously attached but with a different class. Could you please tell me if it's ok? I would appreciate it greatly :) https://code.sololearn.com/ctLtJKo9T4dO/?ref=app
12th Jul 2019, 1:56 PM
Frangiax
Frangiax - avatar
+ 1
You're right ... as always! Ty 🌈🌈🌈🤟
12th Jul 2019, 2:08 PM
Frangiax
Frangiax - avatar
0
I would write the destructor like this: MyString:: ~MyString() { delete[] _st; };
12th Jul 2019, 9:17 AM
Frangiax
Frangiax - avatar