CPP Tutorial



C++ THIS POINTER


this Pointer in C++

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.

📌 Key Point:
The this pointer helps differentiate between **class data members** and **parameters** with the same name.

🔧 Why use this pointer?

  • To resolve **naming conflicts** between local variables and class attributes.
  • To return the current object from a member function (chaining).
  • To pass the current object as a parameter.

📄 Example: Using 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;
}
  

🖨️ Output:

Student name is: Ravi

🔍 Explanation:

  • The constructor has a parameter 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.

⚙️ Method Chaining Example (Optional Advanced)

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
  

🎓 Conclusion

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.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review