Reputation: 107
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!
Upvotes: 4
Views: 239
Reputation: 477338
This is an instance of the common code reuse technique to implement one operator in terms of another.
Suppose we have already defined a compound-plus operator:
class X
{
X & operator+=(const X&);
};
This unary operator allows us to write a += b
, it modifies a
and returns a reference to itself. This is all fine and good. Now if we also want to provide a copying, binary plus opearator a + b
, which returns a the new value by value and leaves both a
and b
unchanged, then we want to take advantage of the code we've already written for the compound operator. We do so by calling the unary operator on a temporary copy of a
:
X X::operator+(const X & b) const { return X(*this) += b; }
^^^^^^^^
temporary copy
This is exactly what your code does, only a bit more verbosely. You could as well have written return MyString(*this) += str;
There are other idioms with follow a similar spirit, such as implementing non-const access in terms of const access, copy-assign in terms of copy-construct and swap, and move-assign in terms of move-construct and swap. It always boils down to avoiding code duplication.
Upvotes: 3
Reputation: 96266
ss
is a new string which gets constructed with a copy constructor from the original string.
Upvotes: 1
Reputation: 23266
From what I can tell that is a copy constructor which creates a new MyString with the contents of the current MyString object.
Upvotes: 1
Reputation: 12204
It's a constructor for MyString
that takes the value of the current object (of type MyString
) as its argument.
Upvotes: 1
Reputation: 372972
This code:
MyString ss(*this);
Says "declare a new variable of type MyString
that's named ss
, and initialize it as a copy of *this
." Inside of a member function, this
is a pointer to the receiver object (the object that the member function is acting on), so *this
is a reference to the receiver object. Consequently, you can read this as "make a new MyString
that's called ss
and is a copy of the receiver object."
The idiom being used here is implementing operator +
in terms of operator +=
. The idea is to make a copy of the receiver object, use operator +=
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!
Upvotes: 11