`this` — C++ Keyword
`this` — C++ Keyword
The this keyword in C++: a pointer to the current object inside a non-static member function.
`this` — C++ Keyword
The this keyword in C++: a pointer to the current object inside a non-static member function.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
thisA 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).
this // pointer to current object
*this // the object itself
this->member // equivalent to member (for clarity or disambiguation)
#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
}
this is not available in static member functions.this (or *this for a copy) in a lambda allows the lambda to access the enclosing object.this parameters (this T& self) are supported for deducing polymorphic member functions.thisint 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;
}