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
9 Antworten
+ 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
+ 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)?
+ 1
Thank you! You're my lifesavers! Have a great day
+ 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
+ 1
You're right
... as always!
Ty 🌈🌈🌈🤟
0
I would write the destructor like this:
MyString:: ~MyString() {
delete[] _st;
};