user1363061 user1363061 - 3 months ago 26
C++ Question

Compound assignment and add operator overloading

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!

Answer

First, usually you return a new object from operator+, because the expectation is that calling + on an object does not change the object itself.

MyString MyString::operator+ (const MyString& rhs)  
{  
  // ...

  return MyString(...);  

} 

Note the missing reference (&) from the return type: you are returning the new object by-copy, not by-reference.

Second, if you delete the String at the beginning, you will not be able to copy its contents. Consider this for operator+:

char* tmp = new char[Size + rhs.Size + 1]; // +1 for the terminating '\0'      
for(int i = 0; i < Size ; i++)      
{
  // copy the contents of current object buffer, char-by-char
  tmp[i] = String[i]; 
}
for(int i = 0; i < rhs.Size+1; i++) // +1 to copy the terminating '\0' as well
{      
  // copy the contents of other object buffer, char-by-char
  tmp[i+Size] = rhs.String[i]; 
}
MyString result;
delete[] result.String;
result.String = tmp;
result.Size = Size+rhs.Size;      

return result;

operator+= is a bit more tricky, because you need to manipulate the current object's buffer:

char* tmp = new char[Size + rhs.Size + 1]; // +1 for the terminating '\0'      
for(int i = 0; i < Size ; i++)      
{      
  tmp[i] = String[i]; 
}
for(int i = 0; i < rhs.Size+1; i++) // +1 to copy the terminating '\0' as well
{      
  tmp[i+Size] = rhs.String[i]; 
}
delete[] String;
String = tmp;
Size += rhs.Size;      

return *this;

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 one MyString object 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.

Comments