Implicitly and Explicitly Using the this Pointer to Access an Object’s Data Members

Figure 9.23 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. In the next example and in Chapter 10, we show some substantial and subtle examples of using this.


 1   // Fig. 9.23: fig09_23.cpp
 2   // Using the this pointer to refer to object members.
 3   #include <iostream>
 4   using namespace std;
 5
 6   class Test
 7   {
 8   public:
 9      explicit Test( int = 0 ); // default constructor
10      void print() const;
11   private:
12      int x;
13   }; // end class Test
14
15   // constructor
16   Test::Test( int value )
17      : x( value ) // initialize x to value
18   {
19      // empty body
20   } // end constructor Test
21
22   // print x using implicit and explicit this pointers;
23   // the parentheses around *this are required
24   void Test::print() const
25   {
26      // implicitly use the this pointer to access the member x
27      cout << "        x = " << x;                             
28
29      // explicitly use the this pointer and the arrow operator
30      // to access the member x                                
31      cout << " this->x = " << this->x;                      
32
33      // explicitly use the dereferenced this pointer and
34      // the dot operator to access the member x         
35      cout << " (*this).x = " << ( *this ).x << endl;   
36   } // end function print
37
38   int main()
39   {
40      Test testObject( 12 ); // instantiate and initialize testObject
41
42      testObject.print();
43   } // end main


        x = 12
  this->x = 12
(*this).x = 12


Fig. 9.23. using the this pointer to refer to object members.

For illustration purposes, member function print (lines 24–36) first prints x by using the this pointer implicitly (line 27)—only the name of the data member is specified. Then print uses two different notations to access x through the this pointer—the arrow operator (->) off the this pointer (line 31) and the dot operator (.) off the dereferenced this pointer (line 35). Note the parentheses around *this (line 35) when used with the dot member selection operator (.). The parentheses are required because the dot operator has higher precedence than the * operator. Without the parentheses, the expression *this.x would be evaluated as if it were parenthesized as *(this.x), which is a compilation error, because the dot operator cannot be used with a pointer.

One interesting use of the this pointer is to prevent an object from being assigned to itself. As we’ll see in Chapter 10, self-assignment can cause serious errors when the object contains pointers to dynamically allocated storage.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.143.65