Assignment operator

Hi I had a question not so long ago and I am not sure I answered it correctly..


Write the assignment operator for the String class. Keep in mind the memory management assumptions implied by the implementation of the default constructor.
1
2
3
4
5
6
7
8
9
10
11
12

class String 
{ 
public: 
    String() { str_ = new char[1]; *str_ = 0; }
    ~String();
    explicit String(const char* str);
    String(const String& other);
    String& operator = (const String& other);
private:
    char* str_;
}; 



To which I answered:
1
2
3
4
5
6
7
8
9
10
11
12
MyString& operator = (const MyString& other)
	{
		delete[] this->str_;  // assume default constructor triggered to create this object and str_ is just a byte with delimeter /0
		size_t size = strlen(other.str); //get the size of the string
		str_ = new char[size];

		strcpy(str_, other.str); //copy char array to current object`s char array

		return *this;

		};
 

I did not fully understand what that phrase meant : "Keep in mind the memory management assumptions implied by the implementation"
It's almost correct. There's a typo on line 7, where you wrote str instead of str_. Also, strcpy() is not the correct function to use, since it copies up to the first null character, but a String may contain more characters after the first null character, because it has an explicit size.
Last edited on
Thanks, what do you mean by explicit size though? Don`t all strings end on delimeter '\0', why would you read or write beyond delimiter at any point?
My bad. I thought I saw a size member somewhere. The code is correct except for that typo.
Topic archived. No new replies allowed.