We have seen that an object's member functions can manipulate the object's data. How do member functions know which object's data members to manipulate? Every object has access to its own address through a pointer called this (a C++ keyword).
- Allows object to access own address
- Not part of object itself; Implicit argument to non-static member function call
- Implicitly reference member data and functions
- Type of this pointer depends on
- Type of object
- Whether member function is const
- In non-const member function of Employee
- this has type Employee * const ; Constant pointer to non-constant Employee object
- In const member function of Employee
- this has type const Employee * const ; Constant pointer to constant Employee object
The program of Figs. 2.18-2.19 demonstrates the implicit and explicit use of the this pointer to enable a member function of class Test to print the private data x of a Test object. The program of Figs. 2.20-2.24 modifies class Time's set functions setTime, setHour, setMinute and setSecond such that each returns a reference to a Time object to enable cascaded member-function calls.
- Cascaded member function calls
- Multiple functions invoked in same statement
- Function returns reference pointer to same object; { return *this; }
- Other functions operate on that pointer
- Functions that do not return references must be called last
Figure 2.18:
this pointer implicitly and explicitly used to access an object's members. (part 1 of 2)
|
Figure 2.19:
this pointer implicitly and explicitly used to access an object's members. (part 2 of 2)
|
Figure 2.20:
Time class definition modified to enable cascaded member-function calls.
|
Figure 2.21:
Time class member-function definitions modified to enable cascaded member-function calls. (part 1 of 3)
|
Figure 2.22:
Time class member-function definitions modified to enable cascaded member-function calls. (part 2 of 3)
|
Figure 2.23:
Time class member-function definitions modified to enable cascaded member-function calls. (part 3 of 3)
|
Figure 2.24:
Cascading member-function calls.
|
2004-07-29