#Previous question #Index of C++ Questions #Next question

The member functions of every object have access to a pointer named this, which points to the object itself. When we call a member function, it comes into existence with the values of this set to the address of the object for which it was called. This pointer is the default hidden and implicit argument of any non-static member function.

Using a ďthisĒ pointer any member function can find out the address of the object of which it is a member. It can also be used to access the data in the object it points to.

The following program shows the working of the this pointer.

class example
{
  private:
  int i;
  
  public:
  void setdata(int i)
  {
    this->i = i;
    cout << "my objectís address is: " << this << endl;
  }
  void showdata()
  {
    cout << "my objectís address is: " << this << endl;
    cout << this->i;
  }
};
int main (int argc, char *argv[])
{
  example e1;
  e1.setdata(10);
  e1.showdata();
}

Output will be:
my objectís address is 0x8fabfff410
my objectís address is 0x8fabfff410
10

We can confirm from output that each time the address of the same object e1 is printed. Since the this pointer contains the address of the object, using it we can reach the data member of the example class.

You have viewed 1 page out of 62. Your C++ learning is 0.00% complete. Login to check your learning progress.

Most popular topics (must visit)

Useful links for students