C++
The this pointer
Learn to access the class itself with the this pointer.
The this pointer
Inside a member function, this is a pointer to the object the function was called on. Writing this->name accesses the object's own member explicitly. This disambiguates when a parameter name matches a member name.
Example: void setName(std::string name) { this->name = name; }. The right-hand name is the parameter; the left-hand this->name is the object's member. Without this, name = name; assigns the parameter to itself; the member does not change.
Chaining calls
A common use of this is method chaining. If a member function returns return *this;, calls can be chained one after another.
Example: Builder& add(int x) { total += x; return *this; }. Usage: builder.add(1).add(2);. Each add returns the same object, so the next call works on the same object. *this is the object the pointer points to.
Exercise Write the setName member with this
Define a Player class. Under public: add std::string name; and the member function void setName(std::string name) { this->name = name; }. In main create an instance, call setName("Alex") and print name with std::cout.
Show example solution
#include <iostream>
#include <string>
class Player {
public:
std::string name;
void setName(std::string name) {
this->name = name;
}
};
int main() {
Player player;
player.setName("Alex");
std::cout << player.name;
return 0;
}
Test yourself
-
What does this->name = name; do?
void setName(std::string name) { this->name = name; }
- Creates a new local variable
- Deletes the parameter
- Updates the object's member with the parameter value
- Does nothing
Show answer
Updates the object's member with the parameter value — this->name is the member, the right-hand name is the parameter.
-
Write the this pointer
void setName(std::string name) { ____->name = name; }
Show answer
void setName(std::string name) { this->name = name; }
-
Match each expression to its meaning
- this
- Pointer to the object
- this->name
- Access to a member
- *this
- Object the pointer points to
- return *this;
- Return the object for chaining
Next lesson: Access modifiers