Please help to complete this execution of an assignment overloading function.
Here is the instruction:
Assignment operator (=) which will copy the source string into the destination string. Note that size of the destination needs to be adjusted to be the same as the source.
Both addition (+) and assignment (=) operators need to be capable of cascaded operations. This means String3 = String1 + String2, or String1 = String2 = String3 should work.
Here is my .cpp file:
int MyString::Length()
{
int counter(0);
while(String[counter] != '\0')
{
counter ++;
}
return (counter);
}
MyString& MyString::operator=(const MyString& rhs)
{
if(this != &rhs)
{
delete [] String;
String = new char[rhs.Length()];
for(int i = 0; i <rhs.Length()+1 ; i++)
{
String[i] = rhs.String[i];
}
}
return *this;
}
It is called in the main.cpp file by:
String1=String2=String3;
I feel as though I am missing something.Help!!
I suppose
Stringis achar*. Perhaps then,Size, which is the new length, needs to be set to the length of rhs, which is the new string. So it should berhs.Size, and not perhaps this->Size, which is likely to be the case. Note that the terminating null character should be considered in the char array size as well.After that you can enter the loop, once again take care of all the characters, and the terminating null character. Given we do not know what
counteris and assuming it is the new string length without the null character (hence, + 1 accounting for it), I suppose there aren’t any problems with the loop.