The this Pointer and Encapsulation
Use the this pointer and enforce encapsulation with private and public access.
What is this?
Inside a non-static member function, this is an implicit pointer to the current object. Use it to disambiguate or to return references.
class Counter {
int n_ = 0;
public:
Counter& add(int x) {
n_ += x; // implicit this
return *this; // chain calls
}
};Implicit Access
You usually do not need to write this->. Member names are looked up automatically — this->n_ and n_ are equivalent.
All lessons in this course
- struct vs class When to Use Each
- Member Variables and Methods
- Constructors and Member Initializer Lists
- The this Pointer and Encapsulation