The this pointer can also be used in the return statement of a member function. In both C and C++, an assignment statement can be treated as an expression, which has the value of what was being assigned. For example, the statement
i = 3;
is an expression with the value 3.
One result of this is that you can chain together multiple assignment statements:
a = b = c;
The assignment operator is right associative, so the expression is evaluated from right to left. This means the expression is equivalent to the following:
a = (b = c);
To make your overloaded class assignments work this way, you must make the assignment function return the result of the assignment. You want the assignment operator to return the object to which it belongs. You get the address of the object from the this pointer.
Returning *this involves a simple modification to the assignment operator (in the operator= function):
String &String::operator=( const String &other )
{
if( &other == this )
return *this;
delete buf;
length = other.length;
buf = new char[length + 1];
strcpy( buf, other.buf );
return *this;
}
With this version of the operator= function, you can chain together assignments of String objects:
herString = yourString = myString;
Note that the function returns a reference to a String. This is more efficient that returning an actual String object; see the section “The Copy Constructor” for more information on returning objects from functions.
The practice of returning *this also explains how the chained cout statements used in previous examples work. You have seen many statements similar to the following:
cout << a << b << c;
The left-shift operator is left-associative, so this expression is evaluated from left to right. The overloaded left-shift operator returns *this, which is the cout object, so each variable is printed successively.