What is the this pointer in C++: Explanation and Example
this pointer is an implicit pointer available inside non-static member functions that points to the object calling the function. It helps access the calling object's members and distinguish between member variables and parameters with the same name.How It Works
Imagine you have a group of identical robots, each with its own toolbox. When a robot performs a task, it needs to know which toolbox to use. In C++, the this pointer acts like a label on the robot's toolbox, pointing to the exact object that called the function.
Inside a class's non-static member function, this is a hidden pointer that holds the address of the current object. This means when you use this, you are referring to the object that invoked the function, allowing you to access or modify its own data members.
This is especially useful when function parameters have the same names as member variables. Using this helps the program know you mean the object's member, not the parameter.
Example
This example shows a class with a member variable and a function that uses the this pointer to set the member variable when the parameter has the same name.
#include <iostream> class Box { public: int length; void setLength(int length) { this->length = length; // 'this->length' is the member, 'length' is the parameter } int getLength() { return this->length; // Access member variable using 'this' } }; int main() { Box box; box.setLength(10); std::cout << "Length of box: " << box.getLength() << std::endl; return 0; }
When to Use
You use the this pointer inside class member functions when you need to refer explicitly to the calling object. Common cases include:
- Distinguishing member variables from parameters or local variables with the same name.
- Returning the current object from a member function to allow chaining calls.
- Passing the current object’s address to other functions or storing it.
For example, in setter functions where parameter names match member variables, this clarifies which variable you mean. It also helps in fluent interfaces where methods return *this to chain multiple calls.
Key Points
thisis an implicit pointer inside non-static member functions.- It points to the object that called the member function.
- It helps resolve naming conflicts between members and parameters.
- You can use
thisto return the current object for method chaining. thiscannot be used in static member functions because they do not belong to any object.
Key Takeaways
this pointer refers to the current object inside non-static member functions.this to access or modify the calling object's members explicitly.this in static member functions.*this enables method chaining in classes.