logo of SA Coder
        Menu
sign in

      References



'this' Pointer



The 'this' pointer in C++ is a pointer that is automatically passed as an implicit argument to a member function. It points to the invoking object, which is the object on which the function is called. This allows the member function to access the member variables and methods of the object it is called on.



Here's a simple example to illustrate how to use the 'this' pointer in C++


copy

#include 
using namespace std;

class MyClass {
  private:
    int x;
  public:
    void setX(int x) {
      this->x = x;
    }
    int getX() {
      return this->x;
    }
};

int main() {
  MyClass myObj;
  myObj.setX(42);
  cout << myObj.getX() << endl;
  return 0;
}



In this example, we define a class called MyClass with a private member variable x and two member functions: setX and getX. The setX function takes an argument x and sets the value of the member variable x to the value of the argument. The getX function returns the value of the member variable x.



Note that we use the 'this' pointer to refer to the member variable x in the setX and getX functions. This is because the member function is called on an object, and the 'this' pointer points to that object.



One common mistake when using the 'this' pointer is forgetting to use it to refer to member variables and methods. Here's an example of how to avoid this mistake


copy

#include 
using namespace std;

class MyClass {
  private:
    int x;
  public:
    void setX(int x) {
      // Wrong: x = x;
      // Right: this->x = x;
    }
    void printX() {
      // Wrong: cout << x << endl;
      // Right: cout << this->x << endl;
    }
};

int main() {
  MyClass myObj;
  myObj.setX(42);
  myObj.printX();
  return 0;
}



In this example, we define a class called MyClass with a private member variable x and two member functions: setX and printX. In the setX function, we use the 'this' pointer to refer to the member variable x. In the printX function, we use the 'this' pointer to refer to the member variable x when printing its value to the console.



Using the 'this' pointer can be a powerful tool in your C++ programming arsenal. With the tips and examples provided in this guide, you'll be able to start using it in your own projects in no time.



Please login first to comment.