C++ this


Example

Within a member function of a class, the keyword this is a pointer to the instance of the class on which the function was called. this cannot be used in a static member function.

struct S {
    int x;
    S& operator=(const S& other) {
        x = other.x;
        // return a reference to the object being assigned to
        return *this;
    }
};

The type of this depends on the cv-qualification of the member function: if X::f is const, then the type of this within f is const X*, so this cannot be used to modify non-static data members from within a const member function. Likewise, this inherits volatile qualification from the function it appears in.

C++11

this can also be used in a brace-or-equal-initializer for a non-static data member.

struct S;
struct T {
    T(const S* s);
    // ...
};
struct S {
    // ...
    T t{this};
};

this is an rvalue, so it cannot be assigned to.