Using the this pointer to refer to object members. - C++ Class

C++ examples for Class:this

Description

Using the this pointer to refer to object members.

Demo Code

#include <iostream> 
using namespace std; 

class Test //from  ww w  .  ja v a2  s.  c om
{ 
public: 
   Test( int = 0 ); // default constructor 
   void print() const; 
private: 
   int x; 
};

// constructor 
Test ::Test( int value ) : x( value ) // initialize x to value 
{ 
}

// print x using implicit and explicit this pointers; the parentheses around *this are required 
void Test::print() const 
{ 
   // implicitly use the this pointer to access the member x 
   cout << "            x = " << x; 

   // explicitly use the this pointer and the arrow operator 
   // to access the member x 
   cout << "\n  this->x = " << this->x; 

   // explicitly use the dereferenced this pointer and 
   // the dot operator to access the member x 
   cout << "\n(*this).x = " << ( *this ).x << endl; 
}

int main() 
{ 
   Test testObject( 12 ); // instantiate and initialize testObject 

   testObject.print(); 
}

Result


Related Tutorials