Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
Your Ad Here
Your Ad Here
this  Pointer

When  several  instances  of  a  class  come  into  life,  it  naturally  follows  that  each  object maintains  its  own  copy  of  the  data  members.  If  this  were  not  the  case,  then  for obvious  reasons  it  would  be  senseless  to  create  more  than  one  instance  of  a  class. In  the  example,  a1  and  a2  are  two  A  objects:


A  a1,  a2 ;


a1  object  has  its  own  set  of  data  members;  and  a2  object  has  its  own  data  set.

On  the  other  hand,  even  though  the  class  member  functions  are  encapsulated  with the data  members  inside  the  class  definition,  it  would  be  very  inefficient  in  terms  of memory  usage  to  replicate  all  of  these  member  functions and  store  the  code  for them within  each  instance.  Consequently,  only  one  instance  of  each  member  function exists, and  must  therefore  be  shared  by  all  of  the  instances  of  the  class.

But  this  poses  a  big  problem  for  the  compiler:  how  can  any  given  member  function of a  class  know  which  instance  it  is  supposed  to  be  working  on?  The  answer  is:  the pointer  this.

The  keyword  this  is  a  hidden  argument  always  passed  to  any  non-static  member function.  Hence,  variable  this  is  a  local  variable  available  in  the  body  of  only  non-static  member  functions.  It  is  initialized  to  point  to  the  object  for  which  the  member function  is  invoked.  For  example,  in  the  call


obj . f ( ) ;


this  is  set  to  & obj.  Static  member  functions  do  not  have  a  this  pointer  because  they are  called  with  no  particular  object  in  mind.  Thus,  a  static  member  function  cannot access  non-static  members.
Even  though  the  this  pointer  is  implicitly  declared,  it  can  be  referred  to  explicitly  in  a function  definition.



For  example,


                                   person &  person : :  greater ( person & x )
                                   {
                                              if ( x . age > age )

                                                                return  x ; //  argument  object
                                              else
                                                                return  * this ;  //  invoking  objet
                                   }



Suppose  we  invoke  this  function  by  the  call


max = A . greater ( B ) ;


This  function  will return  the  object  B ( argument  object )  if  the  age  of  the  person  B  is greater  than  that  of  A.  Otherwise,  it  will return  the  object   A ( invoking  object )  using  the pointer  this.  Remember --  the  this pointer  has  absolutely  no  meaning  outside  the scope of  a  non-static  member  function.