Friday 18 March 2011

this pointer




                                         this pointer
The this pointer is used as a pointer to the class object instance by the member function. The address of the class instance is passed as an implicit parameter to the member functions. The sample below, in this c++ Tutorial shows how to use it. It is a common knowledge that C++ keeps only one copy of each member function and the data members are allocated memory for all of their instances. This kind of various instances of data are maintained use this pointer. Look at the sample below. 
notes on this pointer:
  • this pointer stores the address of the class instance, to enable pointer access of the members to the member functions of the class.
  • this pointer is not counted for calculating the size of the object.
  • this pointers are not accessible for static member functions.
  • this pointers are not modifiable.
  •  
  •  
EXAMPLE:

#include<iostream.h>
class A
{
private:
int a;
public:
void set()
{
this->a=11;
cout<<”\na=”<<this ->a;
cout<<”\na=”<<a;
}
};

void main()
{
A obj;
obj.set();    //here ‘this’ pointer points to obj.
}

Output:
a=11
a=11

this’ pointer always points to the object with respect to which a member function is called.



No comments:

Post a Comment