The C++ solution to not able to return the object that invokes a member function call is the special pointer "this". The this pointer points to the object used to invoke a member function. (Basically, this is passed as a hidden argument to the method.) Thus the function call stock1.topval(stock2) sets this to the address of the stock1 object and makes that pointer available to the topval() method.
Similarly, the function call stock2.topval(stock1) sets this to the address of the stock2 object. In general, all class methods have a this pointer set to the address of the object that invokes the method. Indeed, total_val in topval() is just a shorthand notation for this->total_val. (Recall from earlier blogs that you use the -> operator to access structure members via a pointer. The same is true for class members.)
The this pointer
Each member function, including constructors and destructors, has a this pointer. The special property of the this pointer is that it points to the invoking object. If a method needs to refer to the invoking object as a whole, it can use the expression *this. Using the const qualifier after the function argument parentheses qualifies this as being const; in that case, you can't use this to change the object's value.
What you want to return, however is not this, because this is the address of the object. You want to return the object itself, and that is symbolized by *this. (Recall that applying the dereference operator * to a pointer yields the value to which the pointer points.) Now you can complete the method definition by using *this as an alias for the invoking object:
const Stock & Stock::topval(const Stock & s) const
{
if (s.total_val > total_val)
return s; // argument object
else
return *this; // invoking object
}
The fact that the return type is a reference means that the returned object is the invoking object itself, rather than a copy passed by the return mechanism.
Abonneren op:
Reacties posten (Atom)
Geen opmerkingen:
Een reactie posten