Could someone explain this code? I don’t understand line 3:
MyString MyString::operator+(const MyString &str)
{
MyString ss(*this); //----> explain this part
ss += str;
return ss;
}
Thanks!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This code:
Says “declare a new variable of type
MyStringthat’s namedss, and initialize it as a copy of*this.” Inside of a member function,thisis a pointer to the receiver object (the object that the member function is acting on), so*thisis a reference to the receiver object. Consequently, you can read this as “make a newMyStringthat’s calledssand is a copy of the receiver object.”The idiom being used here is implementing
operator +in terms ofoperator +=. The idea is to make a copy of the receiver object, useoperator +=to add the parameter to the copy, and then to return the copy. It’s a widely-used trick that simplifies the implementation of freestanding operators given implementation of the corresponding compound assignment operator.Hope this helps!