Search This Blog

'this' Pointer

'THIS'       POINTER

In a class, when the objects are decalred, all the data mebers are allcoated separate memory to store their respective values while the member functions are allocated space for once only as shown illustrated by the fgure given below:


That is, multiple instances of the class member function do not exist. The functions work upon differnt set of values depending on the object through which the function is being invoked. 
If member function 1 has to work with data memebr object 1 then how the function will identify that it has to process the value of object1 and not object2 or object3.
The situatio is being sorted with the use of 'this' pointer.  when the object1 of class invokes fmember function1 or memberfunction2 then it automatically passes this pointer to the meber function.
'this ' is the variable that is avaailable in all the member functions of the class and it holds the address of the object that is invoking the non-static member function.
'this' pointer is not available in static member functions.
The use of this ponter may be understood with the following example:

#include<iostream.h>
class stud
{
    int rno;
    char sname[20];
    float marks;

    public:

   void inp( int marks)              
   {   cout<<"\n enter roll number and name : ";
       cin>>rno>>sname;
       this->marks=marks;    // marks is local parameter whereas 
                                      //this->marks is the marks of object calling the function.
    }
    void disp( )
  {   cout<<"\n name : "<<sname;
      cout<<"\n marks : "<<marks;
   }

};     
void main( )
{
    int marks;
    stud s;
    cout<<"\n enter marks of the student ";
    cin>>marks;
    s.inp(marks);
    s.disp( );
}