This Pointer 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.

Definition: this pointer 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.




This pointer in C++

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
using namespace std;
class test
int a=1;

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;;

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


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.