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

‘this’ pointer in C++

Last Updated : 27 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++, ‘this’ pointers is a pointer to the current instance of a class. It is used to refer to the object within its own member functions. In this article, we will learn how to use ‘this’ pointer in C++.

Let’s take a look at an example:

C++
#include <iostream>
using namespace std;

// Class that uses this pointer
class A {
  public:
    int a;
    A(int a) {

        // Assigning a of this object to
        // function argument a
        this->a = a;
    }
    void display() {

        // Accessing a of this object
        cout << "Value: " << this->a;
    }
};

int main() {

    // Checking if this works for the object
    A o(10);
    o.display();

    return 0;
}

Output
Value: 10

Understanding this Pointer

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

CPP
#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.

To explore more about this pointer and object manipulation, check out our Complete C++ Course, where you’ll gain a solid understanding of pointers, classes, and object management.

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.

CPP
#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

CPP
#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

CPP
#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

CPP
#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

CPP
#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

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 = & 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
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: [GFGTABS] C #include<stdio.h> int main() { int arr[5] = { 1, 2, 3, 4, 5 }; int *ptr = arr; printf("%p\n", ptr); return 0; } [/GFGTABS]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 th
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 & operator array is an alias for &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
C | Pointer Basics | Question 1
What is the output of following program? # include <stdio.h> void fun(int x) { x = 30; } int main() { int y = 20; fun(y); printf("%d", y); return 0; } (A) 30 (B) 20 (C) Compiler Error (D) Runtime Error Answer: (B) Explanation: Parameters are always passed by value in C. Therefore, in the above code, value of y is not modified using
1 min read
C | Pointer Basics | Question 2
Output of following program? # include <stdio.h> void fun(int *ptr) { *ptr = 30; } int main() { int y = 20; fun(&y); printf("%d", y); return 0; } (A) 20 (B) 30 (C) Compiler Error (D) Runtime Error Answer: (B) Explanation: The function fun() expects a pointer ptr to an integer (or an address of an integer). It modifies the value
1 min read
C | Pointer Basics | Question 3
Output of following program? #include <stdio.h> int main() { int *ptr; int x; ptr = &x; *ptr = 0; printf(" x = %d\n", x); printf(" *ptr = %d\n", *ptr); *ptr += 5; printf(" x = %d\n", x); printf(" *ptr = %d\n", *ptr); (*ptr)++; printf(" x = %d\n", x); printf(" *ptr = %d\n", *ptr);
2 min read
C | Pointer Basics | Question 4
Consider a compiler where int takes 4 bytes, char takes 1 byte and pointer takes 4 bytes. #include <stdio.h> int main() { int arri[] = {1, 2 ,3}; int *ptri = arri; char arrc[] = {1, 2 ,3}; char *ptrc = arrc; printf("sizeof arri[] = %d ", sizeof(arri)); printf("sizeof ptri = %d ", sizeof(ptri)); printf("sizeof arrc[] =
1 min read
C | Pointer Basics | Question 17
Assume that float takes 4 bytes, predict the output of following program. #include <stdio.h> int main() { float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5}; float *ptr1 = &arr[0]; float *ptr2 = ptr1 + 3; printf("%f ", *ptr2); printf("%d", ptr2 - ptr1); return 0; } (A) 90.500000 3 (B) 90.500000 12 (C) 10.000000 12 (D) 0.5000
1 min read
C | Pointer Basics | Question 6
#include<stdio.h> int main() { int arr[] = {10, 20, 30, 40, 50, 60}; int *ptr1 = arr; int *ptr2 = arr + 5; printf("Number of elements between two pointer are: %d.", (ptr2 - ptr1)); printf("Number of bytes between two pointers are: %d", (char*)ptr2 - (char*) ptr1); return 0; } Assume that an int variable takes 4 bytes and a
2 min read
C | Pointer Basics | Question 7
#include<stdio.h> int main() { int a; char *x; x = (char *) &a; a = 512; x[0] = 1; x[1] = 2; printf("%d\n",a); return 0; } What is the output of above program? (A) Machine dependent (B) 513 (C) 258 (D) Compiler Error Answer: (A) Explanation: Output is 513 in a little endian machine. To understand this output, let integers be sto
1 min read
C | Pointer Basics | Question 8
C/C++ Code int main() { char *ptr = \"GeeksQuiz\"; printf(\"%c", *&*&*ptr); return 0; } (A) Compiler Error (B) Garbage Value (C) Runtime Error (D) G Answer: (D)Explanation: The operator * is used for dereferencing and the operator & is used to get the address. These operators cancel out effect of each other when used one after another. We can a
1 min read
C | Advanced Pointer | Question 1
C/C++ Code void fun(int *p) { int q = 10; p = &q; } int main() { int r = 20; int *p = &r; fun(p); printf(\"%d\", *p); return 0; } (A) 10 (B) 20 (C) Compiler error (D) Runtime Error Answer: (B)Explanation: Inside fun(), q is a copy of the pointer p. So if we change q to point something else then p remains uneffected. If we want to change a local poi
2 min read
C | Advanced Pointer | Question 2
Assume sizeof an integer and a pointer is 4 byte. Output? #include <stdio.h> #define R 10 #define C 20 int main() { int (*p)[R][C]; printf("%d", sizeof(*p)); getchar(); return 0; } (A) 200 (B) 4 (C) 800 (D) 80 Answer: (C) Explanation: Output is 10*20*sizeof(int) which is “800″ for compilers with integer size as 4 bytes. When a point
1 min read
C | Pointer Basics | Question 17
#include<stdio.h> void fun(int arr[]) { int i; int arr_size = sizeof(arr)/sizeof(arr[0]); for (i = 0; i < arr_size; i++) printf("%d ", arr[i]); } int main() { int i; int arr[4] = {10, 20 ,30, 40}; fun(arr); return 0; } (A) 10 20 30 40 (B) Machine Dependent (C) 10 20 (D) Northing Answer: (B) Explanation: In C, array parameters are
2 min read
C | Pointer Basics | Question 10
The reason for using pointers in a C program is (A) Pointers allow different functions to share and modify their local variables. (B) To pass large structures so that complete copy of the structure can be avoided. (C) Pointers enable complex “linked\" data structures like linked lists and binary trees. (D) All of the above Answer: (D)Explanation: S
1 min read
C | Pointer Basics | Question 11
C/C++ Code #include void f(int *p, int *q) { p = q; *p = 2; } int i = 0, j = 1; int main() { f(&i;, &j;); printf(\"%d %d", i, j); getchar(); return 0; } (A) 2 2 (B) 2 1 (C) 0 1 (D) 0 2 Answer: (D)Explanation: See below f() with comments for explanation. /* p points to i and q points to j */ void f(int *p, int *q) { p = q; /* p also points to j now */
1 min read
C | Pointer Basics | Question 12
Consider this C code to swap two integers and these five statements after it: void swap(int *px, int *py) { *px = *px - *py; *py = *px + *py; *px = *py - *px; } S1: will generate a compilation error S2: may generate a segmentation fault at runtime depending on the arguments passed S3: correctly implements the swap procedure for all input pointers r
1 min read
C | Pointer Basics | Question 13
int f(int x, int *py, int **ppz) { int y, z; **ppz += 1; z = **ppz; *py += 2; y = *py; x += 3; return x + y + z; } void main() { int c, *b, **a; c = 4; b = &c; a = &b; printf("%d ", f(c, b, a)); return 0; } (A) 18 (B) 19 (C) 21 (D) 22 Answer: (B) Explanation: Let us understand this line by line /* below line changes value of c to
1 min read
C | Pointer Basics | Question 14
Predict the output of following program #include<stdio.h> int main() { int a = 12; void *ptr = (int *)&a; printf("%d", *ptr); getchar(); return 0; } (A) 12 (B) Compiler Error (C) Runt Time Error (D) 0 Answer: (B) Explanation: There is compiler error in line "printf("%d", *ptr);". void * type pointers cannot be de-referenced. We
1 min read
C | Advanced Pointer | Question 3
#include <stdio.h> int main() { int a[5] = {1,2,3,4,5}; int *ptr = (int*)(&a+1); printf("%d %d", *(a+1), *(ptr-1)); return 0; } (A) 2 5 (B) Garbage Value (C) Compiler Error (D) Segmentation Fault Answer: (A) Explanation: The program prints “2 5″. Since compilers convert array operations in pointers before accessing the array ele
1 min read
C | Advanced Pointer | Question 4
#include <stdio.h> char *c[] = {"GeksQuiz", "MCQ", "TEST", "QUIZ"}; char **cp[] = {c+3, c+2, c+1, c}; char ***cpp = cp; int main() { printf("%s ", **++cpp); printf("%s ", *--*++cpp+3); printf("%s ", *cpp[-2]+3); printf("%s ", cpp[-1][-1]+1); return 0; } (A) TEST s
1 min read
C | Pointer Basics | Question 15
#include<stdio.h> void swap (char *x, char *y) { char *t = x; x = y; y = t; } int main() { char *x = "geeksquiz"; char *y = "geeksforgeeks"; char *t; swap(x, y); printf("(%s, %s)", x, y); t = x; x = y; y = t; printf("\n(%s, %s)", x, y); return 0; } (A) (geeksquiz, geeksforgeeks) (geeksforgeeks, geeksqui
1 min read
C | Pointer Basics | Question 16
#include <stdio.h> int main() { int arr[] = {1, 2, 3, 4, 5}; int *p = arr; ++*p; p += 2; printf("%d", *p); return 0; } (A) 2 (B) 3 (C) 4 (D) Compiler Error Answer: (B) Explanation: The expression ++*p is evaluated as "++(*p)" . So it increments the value of first element of array (doesn't change the pointer p). When p += 2 is done,
1 min read
C | Advanced Pointer | Question 5
Predict the output #include <string.h> #include <stdio.h> #include <stdlib.h> void fun(char** str_ref) { str_ref++; } int main() { char *str = (void *)malloc(100*sizeof(char)); strcpy(str, "GeeksQuiz"); fun(&str); puts(str); free(str); return 0; } (A) GeeksQuiz (B) eeksQuiz (C) Garbage Value (D) Compiler Error Answer
1 min read
C | Advanced Pointer | Question 7
Assume that the size of int is 4. #include <stdio.h> void f(char**); int main() { char *argv[] = { "ab", "cd", "ef", "gh", "ij", "kl" }; f(argv); return 0; } void f(char **p) { char *t; t = (p += sizeof(int))[-1]; printf("%s\n", t); } (A) ab (B) cd (C) ef (D) gh Answer: (D)
1 min read
Practice Tags :
three90RightbarBannerImg