Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 171 ยท Object-Oriented Programming

The this Pointer

Understand the C++ this pointer - how member functions find their object, this-> for shadowed names, returning *this for chaining, capturing this in lambdas, and C++23 deducing this.

A class's member functions exist only once in the compiled program, no matter how many objects you create. So when you call a.area() and then b.area(), how does the same machine code know to read a's width the first time and b's the second? The answer is a hidden parameter: every non-static member function receives the address of the object it was called on, and inside the function that address is available as this.

Most of the time you never write this; the compiler uses it for you whenever you name a member. But knowing it's there explains a lot about how classes work, and writing it explicitly solves real problems: telling members apart from parameters with the same name, detecting self-assignment, passing the current object to other code, and returning *this so calls can be chained. C++23 adds a new way to spell the object parameter, called deducing this, which removes duplicate code. You should be comfortable with Pointers and Classes and Objects before starting.

The hidden parameter

Conceptually, the compiler rewrites a member function as a free function with an extra first parameter. This class:

C++
class Counter {
public:
    void add(int amount) { value_ += amount; }
private:
    int value_ = 0;
};

counter.add(5);

compiles to roughly the same code as:

C++
void Counter_add(Counter* this_, int amount) { this_->value_ += amount; }

Counter_add(&counter, 5);

Every time you write a member name like value_ inside a member function, the compiler reads it as this->value_. The program below prints this from inside a member function and compares it with the object's address.

C++ this is the address of the object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The addresses change from run to run, but within a run this always equals the address of the object the function was called on.

A few precise facts about this:

  • It's a prvalue (a pure value, like the result of a + b), so you can't assign to it or take its address.
  • Inside a member function of class T, its type is T*. Inside a const member function it's const T*, which is exactly why a const function can't modify members (const Member Functions and mutable).
  • Static member functions have no this: they aren't called on an object (Static Members).
  • this is never null in a valid program. Calling a member function through a null pointer is undefined behavior before the function even starts, so checks like if (this == nullptr) are meaningless and compilers remove them.

Writing this explicitly

Telling members and parameters apart

If a parameter or local variable has the same name as a member, it shadows the member: the plain name means the parameter. this->name still reaches the member.

C++
class Player {
public:
    void rename(const std::string& name) {
        this->name = name;      // member = parameter
        // name = name;         // BUG: assigns the parameter to itself
    }
private:
    std::string name;
};

This works, but many C++ codebases avoid the situation instead by naming members distinctively (name_, m_name or mName), as this course does. In constructors you don't even need this->: in an initializer list, name{name} initializes the member name from the parameter name, because the part before the brace can only be a member.

Passing the current object to other code

Sometimes an object needs to hand itself to another function or register itself somewhere. *this is the object itself (a reference-like lvalue); this is its address.

C++ Using this to pass the current object and detect self-use

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Comparing &other == this is the standard way to detect that two references name the same object. You'll use it in copy assignment operators, where x = x; must not destroy the data before copying it (Copy Constructors and Copy Assignment).

Returning *this for method chaining

A member function that returns a reference to the current object lets callers chain calls: builder.a().b().c(). Each call returns the same object, so the next call operates on it. This is how std::cout << a << b works, and it's the backbone of the builder style for configuring objects.

The return type must be a reference (T&). Return T by value instead and each call returns a copy, so the rest of the chain modifies copies and the original object only sees the first call.

C++ Chaining with return *this, and the by-value bug

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

c.add(1) changes c and returns a copy of it; .add(2) and .add(3) then modify temporary copies that are thrown away, so c ends at 1. Changing the return type to BrokenCounter& fixes it. The same convention applies to compound assignment operators such as +=, which return *this by reference so a += b behaves like it does for built-in types (Operator Overloading).

this in lambdas

A lambda written inside a member function can use the object's members only if it captures this. There are two ways, with very different lifetimes:

  • [this] captures the pointer. The lambda reads and writes the original object, but it dangles if the lambda outlives the object.
  • [*this] (C++17) captures a copy of the whole object. The lambda is self-contained and safe to keep, but it doesn't see later changes, and copying may be expensive.
C++ Capturing this vs *this

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Capturing with [=] used to capture this implicitly, which made it easy to miss that the lambda depends on the object staying alive. C++20 deprecates that implicit capture; write [=, this] or [=, *this] to make your intent explicit. A [this] lambda handed to a thread, a timer or an event queue is a classic source of use-after-free bugs (Lambda Expressions).

Deducing this: explicit object parameters (C++23)

C++23 lets you declare the object parameter explicitly, as the first parameter of a member function, marked with this. Inside the function you then use that parameter (commonly named self) instead of this, and there is no implicit this at all:

C++
class Box {
public:
    int volume(this const Box& self) {           // explicit object parameter
        return self.w_ * self.h_ * self.d_;       // must use self.; no implicit this
    }
private:
    int w_ = 1, h_ = 1, d_ = 1;
};

That alone is just new spelling. The power comes from making the parameter a template: this auto&& self (or template <typename Self> ... (this Self&& self)) deduces whether the function was called on a const object, a non-const object, an lvalue or an rvalue. One function can replace a whole family of near-identical overloads.

C++ One function instead of const and non-const overloads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

When at is called on inv, Self is Inventory; through view, it is const Inventory, so self.items_[index] is a const std::string& and the assignment in the comment fails, exactly as with a hand-written const overload.

Deducing this also gives lambdas a name for themselves, so a lambda can finally call itself recursively without std::function:

C++ A recursive lambda with deducing this

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Other uses you'll meet later include writing the CRTP pattern without a template base class (Design Patterns in C++) and forwarding *this efficiently from rvalue objects. Support: GCC 14+, Clang 18+ and MSVC 17.2+ implement explicit object parameters, so check your compiler before relying on them in shared code.

Common mistakes

  • Returning *this by value from a function meant for chaining. Return T&.
  • Writing name = name; in a setter whose parameter shadows a member. Use this->name = name or, better, distinct member names.
  • Capturing [this] in a lambda that outlives the object. Capture [*this], capture only the members you need by value, or hold the object in a std::shared_ptr and capture a weak_ptr.
  • Handing out this from a constructor. The object isn't fully constructed yet; code that receives the pointer and calls virtual functions or reads later members sees an incomplete object.
  • Testing this == nullptr. It can't be true in a valid program, so the check is removed by the optimizer and protects nothing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Inside a const member function of class Widget, what is the type of this?

    In a const member function this points to a const object, which is why such a function can't modify members. this is always a pointer, never a reference.
  2. 2. A setter is written void set_size(int size) { size = size; } and the class has a member named size. What happens?

    The parameter shadows the member, so both names refer to the parameter. Write this->size = size, or use a distinct member name like size_.
  3. 3. Counter add(int n) { value_ += n; return *this; } What does c.add(1).add(2).add(3); leave in c if value_ started at 0?

    Only the first call runs on c. It returns a copy, so the later calls modify temporary copies. Returning Counter& makes the chain work on c and gives 6.
  4. 4. A member function returns a lambda that is stored and called after the object has been destroyed. Which capture is safe?

    [*this] copies the whole object into the lambda, so the lambda doesn't depend on the original. [this], [&] and pre-C++20 [=] all capture the pointer, which dangles.
  5. 5. What is the main benefit of a member function declared as template <typename Self> auto& get(this Self& self)?

    The explicit object parameter deduces the object's type, including const. The same body serves both cases, so you don't have to duplicate const and non-const versions.

Summary

  • Every non-static member function receives a hidden pointer to its object, available as this. Naming a member x inside a member function means this->x.
  • this has type T*, or const T* in a const member function. It can't be reassigned, isn't available in static member functions and is never null in a valid program.
  • Use this->member to reach a member shadowed by a parameter, *this to pass the current object along, and &other == this to detect self-assignment or self-transfer.
  • Return *this by reference (T&) to enable method chaining; returning by value chains on copies.
  • In lambdas, [this] captures a pointer (live but can dangle) and [*this] captures a copy (safe to keep). Implicit capture of this with [=] is deprecated in C++20.
  • C++23's explicit object parameter (this Self& self) replaces duplicate const/non-const overloads and lets lambdas call themselves recursively.

Next: const Member Functions and mutable, where you'll see how const on a member function shapes the type of this and what your class promises.