Learn C++
#include "oopbasics/this.hpp"

The this Pointer in C++

//concept

Inside any non-static member function, this is a pointer to the object the call is running on — this->balance names the caller's balance explicitly. Most code never writes it (members resolve implicitly), but three idioms need it: disambiguating parameters that shadow members, returning *this for method chaining, and passing the object's own address outward.

this is a prvalue pointer (type T* inside T, const T* inside const methods) — you can't reseat it, and using it after the object dies is the usual dangling-pointer story in miniature.

//how it works
1

Implicit object, explicit pointer

Every non-static method secretly receives its object; this names it — balance and this->balance are the same storage.

2

Shadow rescue

With a parameter named like the member (name = name; assigns to itself!), this->name = name; targets the member correctly.

3

Chaining via *this

Returning *this by reference (Builder& setX(...) { ...; return *this; }) enables a.setX(1).setY(2); call chains.

4

Const-correct flavor

In const methods this is const T*, so mutation attempts fail — the compiler enforces read-only access automatically.

//example
#include <iostream>
#include <string>
 
class Dog {
public:
std::string name;
Dog& rename(const std::string& name) {
this->name = name;
return *this;
}
};
 
int main() {
Dog d;
d.rename("Rex").rename("Max");
std::cout << d.name << std::endl;
return 0;
}
Output
Max
1The parameter shadows the member, so this->name selects the member while bare name means the parameter.
2Returning *this hands back the same object by reference, letting .rename("Max") chain onto the result.
3Max prints — the second chained call overwrote the first rename.
//use cases
Fixing member/parameter name collisions without renaming either side
Fluent builder APIs that chain setters through returned *this
Handing your own address to callbacks, registries, and observers
Reading const-method errors as the compiler protecting *this from writes

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.