In C++, the this
pointer is an implicit pointer available inside all **non-static member functions**. It points to the **current object** — the object that is calling the method.
this
pointer helps differentiate between **class data members** and **parameters** with the same name.
this
Pointer#include <iostream> using namespace std; class Student { public: string name; Student(string name) { this->name = name; // Resolving naming conflict } void display() { cout << "Student name is: " << this->name << endl; } }; int main() { Student s1("Ravi"); s1.display(); return 0; }
Student name is: Ravi
name
which is the same as the class attribute name
.this->name
refers to the class variable.name
on the right side of =
refers to the parameter.You can return this
to allow chaining multiple function calls:
class Demo { int x; public: Demo& setX(int x) { this->x = x; return *this; } void show() { cout << "Value of x is: " << x << endl; } }; Demo d; d.setX(10).show(); // Chaining
The this
pointer is essential for writing clean, unambiguous code in object-oriented C++. It's automatically available inside all member functions and helps manage class data clearly.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!