Sunday, 23 June 2013

what is this pointer in c++

"this pointer " , is an unique pointer is automatically passed to a member function. the pointer  this , acts as an implict argument to all the member functions.

Consider following example

class ABC
{
       int a;

};

the private variable 'a'  can  be used directly inside a  member function

a = 123;
we can also use the above statement   to  do the same jobs
this->a = 123;

since c++ permits the use of shorthand form a =123, we have not been using the pointer  this explicitely so far, However, we have been implicitely using pointer this ,  when overloading the operators using member function


One important application of the pointer this  is to return it points to. For example

 return *this;

Inside any member  function will return the object that invoked the function. This statement assumes importance when we want  to compare two or more object inside a member function
and return the thinking object as a result
Example
      
      person& person :: greater(person & x)
      {
                     if( x.age > age)
                                  return x;
                    else
                      return *this;
      }

NOTE:-  whenever we call any of the member function of the class then  this pointer always pass by default in the function which keeps address of the calling object.


            
                      

    




0 comments:

Post a Comment