`this` — C++ Keyword

`this` — C++ Keyword

The this keyword in C++: a pointer to the current object inside a non-static member function.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

this

A prvalue expression that evaluates to a pointer to the current object inside a non-static member function. Its type is T* (or const T* in a const member function).

Syntax

this            // pointer to current object
*this           // the object itself
this->member    // equivalent to member (for clarity or disambiguation)

Example

#include <print>

class Counter {
    int value_;

public:
    explicit Counter(int v) : value_(v) {}

    // Method chaining via *this
    Counter& add(int n) {
        value_ += n;
        return *this;
    }

    Counter& multiply(int n) {
        value_ *= n;
        return *this;
    }

    // Disambiguate when parameter shadows member
    void set(int value_) {   // parameter shadows member
        this->value_ = value_;
    }

    int value() const { return value_; }
};

int main() {
    Counter c{5};
    c.add(3).multiply(2);     // 16 (method chaining)
    std::println("{}", c.value());   // 16

    c.set(100);
    std::println("{}", c.value());   // 100
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}