this Pointer in C++

In this tutorial, we will briefly discuss the ‘this’ pointer in C++.

The ‘this’ pointer is a special pointer through which each object of a class has access to its own address.

Why do we use ‘this’ pointer?

There may be one copy of each class’s functionality, but there can be many objects of the same class. We use ‘this’ pointer to know which object’s data members to manipulate.

C++ uses a special keyword called this to represent an object that invokes a member function. For example, if an object O1 of a class invokes the function O1.input(), the function call will set the pointer this to the address of O1.

The ‘this’ pointer is passed as an implicit argument to all non-static member functions.

Uses of ‘this’ pointer in C++

  • Returning an object.

one application of the ‘this’ pointer is that it returns the object it points to. For instance, the statement

return *this;

in a member function will return the object that invoked the function.

  • Accessing an object’s data members.

We can use the ‘this’ pointer to implicitly or explicitly to enable a member function of the class to print its private data. The syntax looks somewhat like this:

cout<<"x= "<<x; //implicitly using the this function to access the value x
cout<<"this->x= "<<this->x; //explicitly using this pointer to access member x.
  • Distinguishing data members.

This unique pointer is used to distinguish local variables from parameters passed to a function.

Type of the ‘this’ pointer:

The type of the ‘this’ pointer depends on the type of object and whether the member function in which ‘this’ is used is declared const or not.

Sample program to demonstrate the use of ‘this’ pointer in C++:

#include<iostream>
using namespace std;
class stu
{
private:
    int rno;
    int marks;
public:
    void get_det(int r,int m)
    {
      this->rno=r;
      this->marks=m;
    }
    void show_det()
    {
        cout<<"roll no. is: "<<rno<<endl;
        cout<<"marks are: "<<marks<<endl;
        cout<<"address of the current object is: "<<this;
    }

};
int main()
{
    stu student1;
    student1.get_det(21,89);
    student1.show_det();
    return 0;
}

The output will look like this:

roll no. is: 21
marks are: 89
address of the current object is: 0x6dfee8
Process returned 0 (0x0)   execution time : 0.016 s
Press any key to continue.

With this, we come to the end of this tutorial.

Also read: Inheritance in C++

Leave a Reply

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