The Wayback Machine - https://web.archive.org/web/20240626125158/https://www.geeksforgeeks.org/this-pointer-in-c/
Open In App

‘this’ pointer in C++

Last Updated : 09 Aug, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

To understand ‘this’ pointer, it is important to know how objects look at functions and data members of a class.

  1. Each object gets its own copy of the data member.
  2. All-access the same function definition as present in the code segment.

Meaning each object gets its own copy of data members and all objects share a single copy of member functions.
Then now question is that if only one copy of each member function exists and is used by multiple objects, how are the proper data members are accessed and updated?
The compiler supplies an implicit pointer along with the names of the functions as ‘this’.
The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name).
For a class X, the type of this pointer is ‘X* ‘. Also, if a member function of X is declared as const, then the type of this pointer is ‘const X *’ (see this GFact)

In the early version of C++ would let ‘this’ pointer to be changed; by doing so a programmer could change which object a method was working on. This feature was eventually removed, and now this in C++ is an r-value.
C++ lets object destroy themselves by calling the following code :




delete this;


As Stroustrup said ‘this’ could be the reference than the pointer, but the reference was not present in the early version of C++. If ‘this’ is implemented as a reference then, the above problem could be avoided and it could be safer than the pointer.

Following are the situations where ‘this’ pointer is used:

1) When local variable’s name is same as member’s name




#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

For constructors, initializer list can also be used when parameter name is same as member’s name.



2) To return reference to the calling object




/* Reference to the calling object can be returned */ 
Test& Test::func ()
{
   // Some processing
   return *this;
} 


When a reference to a local object is returned, the returned reference can be used to chain function calls on a single object.




#include<iostream>
using namespace std;
  
class Test
{
private:
  int x;
  int y;
public:
  Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
  Test &setX;(int a) { x = a; return *this; }
  Test &setY;(int b) { y = b; return *this; }
  void print() { cout << "x = " << x << " y = " << y << endl; }
};
  
int main()
{
  Test obj1(5, 5);
  
  // Chained function calls.  All calls modify the same object
  // as the same object is returned by reference
  obj1.setX(10).setY(20);
  
  obj1.print();
  return 0;
}


Output:

x = 10 y = 20



Exercise:
Predict the output of following programs. If there are compilation errors, then fix them.

Question 1




#include<iostream>
using namespace std;
  
class Test
{
private:
  int x;
public:
  Test(int x = 0) { this->x = x; }
  void change(Test *t) { this = t; }
  void print() { cout << "x = " << x << endl; }
};
  
int main()
{
  Test obj(5);
  Test *ptr = new Test (10);
  obj.change(ptr);
  obj.print();
  return 0;
}




Question 2




#include<iostream>
using namespace std;
  
class Test
{
private:
  int x;
  int y;
public:
  Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
  static void fun1() { cout << "Inside fun1()"; }
  static void fun2() { cout << "Inside fun2()"; this->fun1(); }
};
  
int main()
{
  Test obj;
  obj.fun2();
  return 0;
}




Question 3




#include<iostream>
using namespace std;
  
class Test
{
private:
  int x;
  int y;
public:
  Test (int x = 0, int y = 0) { this->x = x; this->y = y; }
  Test setX(int a) { x = a; return *this; }
  Test setY(int b) { y = b; return *this; }
  void print() { cout << "x = " << x << " y = " << y << endl; }
};
  
int main()
{
  Test obj1;
  obj1.setX(10).setY(20);
  obj1.print();
  return 0;
}




Question 4




#include<iostream>
using namespace std;
  
class Test
{
private:
  int x;
  int y;
public:
  Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
  void setX(int a) { x = a; }
  void setY(int b) { y = b; }
  void destroy()  { delete this; }
  void print() { cout << "x = " << x << " y = " << y << endl; }
};
  
int main()
{
  Test obj;
  obj.destroy();
  obj.print();
  return 0;
}




Previous Article
Next Article

Similar Reads

Difference between passing pointer to pointer and address of pointer to any function
In this article, the differences between passing “pointer to pointer” and “address of pointer” to a function. In C or C++ Programming Language, it is known that pointers hold the address of the variables or any memory location. If pointers are pointed to the memory location, it can be used to change the value of the variable. As for functions, any
3 min read
C++ Pointer To Pointer (Double Pointer)
In C++ a Pointer is a variable that is used to store the memory address of other variables. It is a variable that points to a data type (like int or string) of the same type and is created with the * operator. Syntax of a Pointer in C++: data_type_of_pointer *name_of_variable = &amp; normal_variable; What is a Pointer to a Pointer or Double Pointer
4 min read
C - Pointer to Pointer (Double Pointer)
Prerequisite: Pointers in C The pointer to a pointer in C is used when we want to store the address of another pointer. The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double-pointers. We can use a pointer to a pointer to cha
5 min read
What is a Pointer to a Null pointer
NULL pointer in C At the very high level, we can think of NULL as a null pointer which is used in C for various purposes. Some of the most common use cases for NULL are To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet. C/C++ Code int* pInt = NULL; To check for a null pointer before accessing an
2 min read
Difference between Dangling pointer and Void pointer
Dangling pointer: A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer. There are three different ways where Pointer acts as a dangling pointer: By deallocating memoryFunction CallWhen the variable goes out of scope Void pointer: Void pointer is a specific pointer type – void * – a pointer that point
2 min read
Pointer to an Array | Array Pointer
Prerequisite: Pointers Introduction  Consider the following program:  C/C++ Code #include&lt;stdio.h&gt; int main() { int arr[5] = { 1, 2, 3, 4, 5 }; int *ptr = arr; printf(&quot;%p\n&quot;, ptr); return 0; } In the above program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer that can po
9 min read
How to declare a pointer to a function?
While a pointer to a variable or an object is used to access them indirectly, a pointer to a function is used to invoke a function indirectly. Well, we assume that you know what it means by a pointer in C. So how do we create a pointer to an integer in C? Huh..it is pretty simple... int *ptrInteger; /*We have put a * operator between int and ptrInt
2 min read
Pointer vs Array in C
Most of the time, pointer and array accesses can be treated as acting the same, the major exceptions being: 1. the sizeof operator sizeof(array) returns the amount of memory used by all elements in the array sizeof(pointer) only returns the amount of memory used by the pointer variable itself 2. the &amp; operator array is an alias for &amp;array[0
1 min read
Type of 'this' Pointer in C++
In C++, this pointer refers to the current object of the class and passes it as a parameter to another method. 'this pointer' is passed as a hidden argument to all non-static member function calls. Type of 'this' pointer The type of this depends upon function declaration. The type of this pointer is either const ExampleClass * or ExampleClass *. It
2 min read
How to write C functions that modify head pointer of a Linked List?
Consider simple representation (without any dummy node) of Linked List. Functions that operate on such Linked lists can be divided into two categories: 1) Functions that do not modify the head pointer: Examples of such functions include, printing a linked list, updating data members of nodes like adding given a value to all nodes, or some other ope
4 min read
Practice Tags :
three90RightbarBannerImg