I need help with both of my operator overloading functions presented below. I’m unsure of how I can implement this without actually using the assignment in the function definitions.
Code for operator + in my .cpp file:
MyString& MyString::operator +(const MyString& rhs)
{
delete [] String;
String = new char[rhs.Size];
Size = rhs.Size;
// needs to be a loop for cascading +
// so that String1=String2+String3+String4 will work
for(int i = 0; i < rhs.Size+1 ; i++)
{
// String[i] + rhs.String[i]; ???
}
return *this;
}
Code for += operator in .cpp file:
MyString& MyString::operator+=(const MyString& rhs)
{
delete [] String;
String = new char[rhs.Size];
String = String + rhs.String;
return *this;
}
Call from main.cpp:
String1 = String2 + String3 + String4;
String1.Print ();
String2 += String3;
String2.Print ();
I know my .cpp file codes are wrong, some insight would be great!
First, usually you return a new object from
operator+, because the expectation is that calling + on an object does not change the object itself.Note the missing reference (
&) from the return type: you are returning the new object by-copy, not by-reference.Second, if you
deletetheStringat the beginning, you will not be able to copy its contents. Consider this foroperator+:operator+=is a bit more tricky, because you need to manipulate the current object’s buffer:Update: I assume you also call
delete[]in the class destructor — which you should. It is also not hard to imagine, you will want to perform assingment from oneMyStringobject to another. This will lead to cosider the rule of three: If you need any one of desgtructor, copy-constructor or assignment operator, you most likely need all three.