0Pricing
C++ Academy · Lesson

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

  1. struct vs class When to Use Each
  2. Member Variables and Methods
  3. Constructors and Member Initializer Lists
  4. The this Pointer and Encapsulation
← Back to C++ Academy