C++ The this Pointer

‮w‬ww.theitroad.com

In C++, the this pointer is a pointer to the current object. It is a special keyword that can be used inside a class to refer to the object that the function is being called on. The this pointer is a pointer to the memory address of the object that the function is a member of, and can be used to access the member variables and member functions of the object.

Here's an example of a class that uses the this pointer:

class MyClass {
  public:
    int myInt;
    double myDouble;
    MyClass(int value = 0, double dvalue = 0.0) {
      this->myInt = value;
      this->myDouble = dvalue;
    }
    void print() {
      std::cout << "myInt = " << this->myInt << ", myDouble = " << this->myDouble << std::endl;
    }
};

In this example, the class MyClass has a constructor that initializes the member variables myInt and myDouble using the this pointer. The constructor takes two parameters, value and dvalue, and uses the this pointer to assign the values of these parameters to the member variables.

The print member function of the MyClass class also uses the this pointer to access the member variables of the current object. The print function outputs the values of the member variables myInt and myDouble using the this pointer.

You can create an object of the MyClass class and call the print member function like this:

MyClass obj(42, 3.14);
obj.print();

In this example, we've created an object of the MyClass class, initialized with the values 42 and 3.14, and called the print member function to output the values of the member variables.

The this pointer is useful in situations where you need to refer to the current object, such as when you have multiple objects of the same class and need to distinguish between them, or when you need to pass the current object as a parameter to another function. The this pointer can also be used to avoid naming conflicts between member variables and function parameters.