this
,
so why even have this
be available explicitly?
Good question. That's why the answer is a bit long.
Sometimes, we need to specify the object (that invokes a member function). This is somewhat rare, but it happens. Let us consider the following class (that is somewhat useless):
class Z { private: int i; public: Z &inc(void); }
The return type Z &
means that the function returns ``a reference
to a Z''. It is kind of like ``a pointer to a Z''. However, with a reference,
you don't have to dereference, and you cannot treat it as an array.
The definition of Z::inc
may look like this:
Z &Z::inc(void) { i = i + 1; return *this; }
What is it returning? It is returning a reference to the object that invoked
the member function. Consequently, we can treat the return value of
Z::inc
like any object of class Z
. This makes it possible to
do this following:
{ class Z myZ; myZ.inc().inc().inc().inc(); }
Or, if you prefer parantheses to specify operator priority:
{ class Z myZ; (((myZ.inc()).inc()).inc()).inc(); }
Functionally, it is the same as invoking myZ.inc()
four times.
Of course, your next question is why do we want to do this? The answer is operator overloading. It is discussed in another module (0038).
Copyright © 2006-09-12 by Tak Auyeung