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.

Syntax:

this.var_name;

or

this->var_name;
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
#include<iostream>
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;
}

O/P:-

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.