this Pointer in C++

In this tutorials we will study and understand the concept and working of this Pointer in C++

this Pointer in C++
this Pointer in C++

Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object. this pointer can also be used to return its own reference.
Friend functions do not have a this pointer, because friends are not members of a class. Only member functions have a this pointer.
this’ pointer is not available in static member functions as static member functions can be called without any object (with class name).
Following are the situations where ‘this’ pointer is used:

  • When local variable’s name is same as member’s name.
  • To return reference to the calling object.
When local variable’s name is same as member’s name.

Run Online

#include<iostream>
using namespace std;
 
/* local variable is same as a member's name */
class Test
{
private:
   int x;
public:
   void setX (int x)
   {
       // The 'this' pointer is used to retrieve the object's x
       // hidden by the local variable 'x'
       this->x = x;
   }
   void print() { cout << "x = " << x << endl; }
};
 
int main()
{
   Test obj;
   int x = 20;
   obj.setX(x);
   obj.print();
   return 0;
}
Output
x = 20
To return reference to the calling object.

Run Online

#include<iostream>
using namespace std;
class Max
{
    int a;
    public:
        void getdata()
        {
            cout<<"Enter the Value :";
            cin>>a;
        }
        Max &greater(Max &x)
        {
            if(x.a>=a)
                return x;
            else return *this;
        }
        void display()
        {
            cout<<"Maximum No. is : "<<a<<endl;
        }
};
int main()
{
    Max one,two,three;
    one.getdata();
    two.getdata();
    three=one.greater(two);
    three.display();
    
    return 0;
}
Output
Enter the Value :5
Enter the Value :8
Maximum No. is : 8

Leave a Reply

Your email address will not be published. Required fields are marked *