‘this’ pointer with example.
1 minute read
Explain ‘this’ pointer with example.
‘This’ is a keyword which is used to store the address of the object that invokes a member function. Each member function when invoked, a pointer implicitly holds the address of the object itself, and it is called ‘this’ pointer. There is no need for a user to declare the ‘this’ pointer. It is internally defined. When an object is used to invoke a class member function, then the address of that object is automatically assigned to the ‘this’ pointer.
Explicitly using the ‘this’ pointer.
Class simple
{
Int a;
Public:
Void set_data(int x)
{
This->a=x;
}
Void display()
{
Cout<<”a=”<<this->a<<endl;
Cout<<”address of this=”<<this<<endl;
}
};
Int main()
{
Simple e;
e.set_data(5);
e.display();
return 0;
}
Output
a=5
address of this=ox8feefff4