The Wayback Machine - https://web.archive.org/web/20260509233853/https://www.geeksforgeeks.org/cpp/this-pointer-in-c/

'this' pointer in C++

Last Updated : 19 Jan, 2026

In C++, "this" pointer refers to the current object calling a non-static member function. It is used to access class members, resolve name conflicts, and support method chaining. The this pointer is mainly used to:

  • Access data members of the current object
  • Resolve naming conflicts
  • Return the current object for method chaining

Example: The following example demonstrates how this differentiates between a data member and a constructor parameter with the same name.

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

class Student {
    int age;
public:
    Student(int age) {
        this->age = age;  // data member = parameter
    }

    void show() {
        cout << "Age: " << age << endl;
    }
};

int main() {
    Student s(20);
    s.show();
    return 0;
}

Output
Age: 20

Explanation:

  • this->age refers to the data member
  • age refers to the constructor parameter
  • Without "this", the assignment would be ambiguous

Understanding 'this' Pointer

  • 'this' is an implicit (hidden) pointer automatically available in all non-static member functions and It points to the current object that called the function.
  • In a class X, this has type X* (or const X* inside const member functions) and is implicitly passed to non-static member functions.
  • Used to resolve conflicts between local variables and data members, enable method chaining (calling multiple functions in one statement by returning *this) , and pass the current object.
  • Risky operations like delete this; are possible and generally should be avoided.

Applications of 'this' pointer

applications_of_this_pointer
Applications of this pointer

Common Use Cases of this Pointer

  • Resolving name conflicts between data members and parameters
  • Returning the calling object
  • Passing the current object to another function
  • Enabling method chaining

Returning the Current Object Using this

Returning *this allows method chaining, where multiple function calls are made on the same object in a single statement.

Syntax:

ClassName& functionName() {
return *this;
}

Example: Method Chaining Using this

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

class Test {
    int x, 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 obj;
    obj.setX(10).setY(20).print();
    return 0;
}

Output
x = 10 y = 20

Explanation:

  • setX() and setY() return *this
  • Enables chaining: obj.setX(10).setY(20)
  • Improves readability and fluency of code
Comment