Reputation: 738
I'm making my own string class (as an exercise) and I know I need a copy constructor and an overloaded = assignment operator but not sure where to start.
the class is simple and only stores the string e.g.
char* m_string;
I currently have a standard constructor (MyString(const char* str)
) which takes a const char* string
and then allocates the necessary memory via m_string = new char[numChars + 1]
(after counting the number of chars there are in the argument)
Obviously I need to be able to assign one string to another with the assignment operator, but also want to be able to construct a string object from another. i.e.
MyString(const MyString& str)
{
}
In regards to the overload= assignment operator
Do I then get the length of both rhs and lhs in terms of number of characters and then resize the amount of memory depending on whether the rhs is longer or shorter than the lhs?
I don't necessarily want the whole answer as I don't believe you learn anything from just being told the answer but some advice and guidance in the right direction would be appreciated.
Thanks
Upvotes: 2
Views: 8762
Reputation: 5689
The copy constructor has to allocate memory for the payload of str
and then copy the content. This is very much like the constructor you already have, except that the char *
is not given directly as the parameter but is "hidden" in str
.
The assignment operator has to take the already allocated memory into account.
It can either reuse the existing allocated memory. This works if the new content has the same length or is shorter. The terminating \0
will make the additional memory at the end invisible to regular string handling functions.
If the new string is larger, you have to free the old memory and allocate a new block of sufficient size.
this == &rhs
. If you delete memory and then try to read from it, you'll get problems. This allows a = a
to work.a = b = c
to work.Upvotes: 4
Reputation: 12641
Probably this will work
MyString(const MyString & str) {
m_string = new char[str.length() + 1];
. . . /// same as MyString(const char * str)'s definition
}
and for the operator =
operator =(const char * str) {
if (strcmp(mstring, str) == 0) return; /// Optional
delete[] mstring;
mstring = new char[strlen(str) + 1];
. . . /// Same as the constructor
}
Upvotes: 1