Ad

Wednesday, August 15, 2007

What is 'this' Pointer?

Have a look at the following code:


  // program to illustrate 'this'
  // pointer
  #include <iostream.h>

  // class
  class myclass
  {
    int a;

  public:
    myclass(int);
    void show();
  };

  myclass::myclass(int x)
  {
    // same as writing a=10
    this->a=x;
  };

  void myclass::show()
  {
    // same as writing cout<<a;
    cout<<this->a;
  }

  // main
  void main()
  {
    myclass ob(10);

    ob.show();
  }

Now look at the awkward looking lines:

this->a=x;

and

cout<<this->a;

As you can see ‘this’ looks like a pointer to an object which is neither declared neither as a local nor as a global variable. So how the member function is using it?

Actually ‘this’ is a special argument which is passed implicitly to every member function. It points to the specific object of the class that generated the call to that function.

So if we have the following line of code:

  myclass ob1, ob2;
  ob2.show();

then the func function will be passed a ‘this’ pointer pointing to the object that invoked it (i.e. ob2)

Actually there is no use of ‘this’ pointer like this as every member referenced inside a member function will automatically be relative to the object that generated the call to the function.

So

  myclass::myclass(int x)
  {
   this->a=x;
  };

And

  myclass::myclass(int x) 
  { 
    a=x; 
  };

Codes are equal and do the same thing.

This is not to say that ‘this’ pointer has no practical use as it is frequently needed when overloading operators.

NOTE: Please keep in mind that static member functions are not passed the ‘this’ pointer.

Related Articles:

1 comment:

You are free to comment anything, although you can comment as 'Anonymous' it is strongly recommended that you supply your name. Thank You.

Please don't use abusive language.