Pointer this in C++

this Pointer

Incase of class data members and member function data members having the same name and there is a situation you need to access the class data in a member function itself, so this pointer in C++ is very useful in these situations.
This pointer in c++

Pointer this in C++

Definition: this pointer in C++ is used to distinguish data members of the class and member function when having the same name.

 ‘this’ pointer is a constant pointer that holds the memory address of the current object.

Pointer this in C++

Syntax:

this.var_name;

or

this->var_name;

Creating this Pointer

  • In the below program member function show() contains the variable named ‘a’ and also class test contains a variable with the same name ‘a’.
  • The Ambiguity is solved using this pointer, class data is accessed using this->a which gives 1 and function data is accessed normally which gives 10

Example:

Run

#include 
using namespace std;
class test
{
   int a=1;
public:
void show()
{
   int a=10;

 //gives object address 
   cout<<"Current obj address using this:"<<this<<endl;

//class data
   cout<<"Will print class's a value using this:"<<this->a<<endl;

//member function data
   cout<<"a with out this:"<<a<<endl;//member function data
}
 //cout<<"a using this:"<a<<endl;//error:this pointer cannot be used outside the mem function
};

int main()
{
    test t;
    t.show();

    cout<<"current obj address using address:"<<&t<<endl;
}

Output:

current obj address using this:0x6ffe40
a using this:1
a with out this:10
current obj address using address:0x6ffe40

When to use this pointer?

  • This pointer is relevant only when class and member function data are having the same name.
  • This pointer is used for retrieving the current object address even before declaring an object of that class.
  • This pointer returns the address by default in the hexadecimal format.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription