593 pdfsam Cplusplus Primer Plus 4th Edition

This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks The ...

0 downloads 9 Views 10KB Size
This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks

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 usethis 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 dereferencing 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 the returned object is the invoking object itself rather than a copy passed by the return mechanism. Listing 10.7 shows the new header file.

Listing 10.7 stock2.h

// stock2.h -- improved version #ifndef STOCK2_H_ #define STOCK2_H_