# Member functions and this

> A non-static member function is an ordinary function with one extra parameter, the object it is called on. Qualifiers, overloading, `this` and C++23's explicit object parameters all follow from taking that parameter seriously.

- **Source:** C++ Atlas (https://cppatlas.com/topics/member-functions-and-this)
- **Track:** Classes
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [class.mfct] (https://eel.is/c++draft/class.mfct), [class.mfct.non.static] (https://eel.is/c++draft/class.mfct.non.static), [over.match.funcs] (https://eel.is/c++draft/over.match.funcs), [expr.prim.this] (https://eel.is/c++draft/expr.prim.this), [dcl.fct] (https://eel.is/c++draft/dcl.fct), [class.mem] (https://eel.is/c++draft/class.mem), [class.static] (https://eel.is/c++draft/class.static), [dcl.inline] (https://eel.is/c++draft/dcl.inline), [expr.prim.lambda.capture] (https://eel.is/c++draft/expr.prim.lambda.capture)
- **cppreference links:** [Non-static member functions](https://en.cppreference.com/w/cpp/language/member_functions), [The this pointer](https://en.cppreference.com/w/cpp/language/this), [Function declaration (explicit object parameter)](https://en.cppreference.com/w/cpp/language/function), [static members](https://en.cppreference.com/w/cpp/language/static)
- **Prerequisites:** value-categories, overload-resolution

## The one idea

A non-static member function is a function with one more parameter than you wrote: the object it is called on. The standard calls it the **object parameter**. For a classic member function it is implicit, and its type is a reference to the class, shaped by the qualifiers after the parameter list. Since C++23 you may also write it out yourself as an **explicit object parameter**, spelled with `this` in front.

Everything else in this topic is a consequence. `const` after the parameter list changes the type of that hidden parameter, so it can be overloaded on. A ref-qualifier says whether the parameter is an lvalue or rvalue reference. A static member function is the case with no object parameter at all, which is why it has no `this`. And `this` itself is just the address of whatever the hidden reference is bound to.

> **Mental model.** Read `int S::get() const &` as `int get(const S& self)`. Overload resolution treats it that way, with a couple of special cases, and so should you.

## The implicit object parameter and cv-qualifiers

For overload resolution, [over.match.funcs] gives every implicit object member function an implicit object parameter. Without a ref-qualifier its type is "lvalue reference to cv `X`", where cv comes from the function's own qualifiers. The object expression, the thing left of the dot, is the implied argument. Calling a non-const member function on a const object therefore fails for the same reason that binding `const S` to `S&` fails, and overloading on `const` is ordinary overloading on the type of a reference parameter.

```cpp
#include <cstdio>

struct Buffer {
  void data()       { std::puts("non-const"); }
  void data() const { std::puts("const"); }
};

void use(Buffer& b, const Buffer& cb) {
  b.data();   // non-const: exact match for Buffer&
  cb.data();  // const: only candidate that binds const Buffer
}
```

Inside the body, `this` is a prvalue whose type is a pointer to the cv-qualified class: `const Buffer*` in the const overload. A `mutable` member escapes that, and so does anything reached through a pointer member, because constness applies to the object's own members and not to what they point at.

There is one exception that the "it is just a reference" picture does not predict. For a member function declared **without** a ref-qualifier, an rvalue may bind to the implicit object parameter even though the parameter is a non-const lvalue reference. That is why `std::string("abc").append("d")` has always compiled.

> **Standardese.** [over.match.funcs] says that for implicit object member functions declared without a ref-qualifier, even if the implicit object parameter is not const-qualified, an rvalue can be bound to it, provided that in all other respects the argument could be converted to its type.

## Ref-qualifiers: overloading on the object's value category

C++11 added `&` and `&&` after the parameter list. With `&` the object parameter is an lvalue reference and the rvalue exception above no longer applies. With `&&` it is an rvalue reference, so the function is only viable on rvalues. The standard library uses this for accessors such as `std::optional::value`, which returns `T&&` when called on an rvalue optional so that the contained value can be moved out.

You cannot mix the two styles freely. If one overload of a name with a given parameter list has a ref-qualifier, an overload with the same object type and no ref-qualifier is ill-formed. Clang rejects such a pair at the declaration; GCC 16 accepts the declarations and reports an ambiguity at the call.

The surprise is inside the body. A ref-qualifier changes which objects you can call the function on, but `*this` is still an lvalue expression, and so is every member you name. Moving out of an rvalue-qualified function needs an explicit cast.

```cpp
#include <cstdio>
#include <string>
#include <utility>

struct Holder {
  std::string name = "x";
  static void sink(std::string&)  { std::puts("lvalue"); }
  static void sink(std::string&&) { std::puts("rvalue"); }

  void take() && {
    sink(name);                    // lvalue: a named member is an lvalue
    sink(std::move(*this).name);   // rvalue: member of an xvalue is an xvalue
  }
};

int main() { Holder{}.take(); }    // prints lvalue, then rvalue
```

## Explicit object parameters (C++23)

P0847, known as "deducing this", lets you declare the object parameter as the first function parameter, prefixed by `this`. The function is then an **explicit object member function**. It is called with the usual `obj.f()` syntax, but inside it there is no `this` pointer and no implicit member access: you must write `self.x`, exactly as in a free function.

```cpp
#include <type_traits>

struct Base {
  template <class Self>
  int which(this Self&&) {
    return std::is_same_v<std::remove_cvref_t<Self>, Base> ? 1 : 2;
  }
};
struct Derived : Base {};

int demo() {
  Derived d;
  Base& b = d;
  return d.which() * 10 + b.which();   // 21: Self deduces from the static type
}
```

The template parameter is deduced from the object expression, so one function template replaces the const, non-const, lvalue and rvalue overloads that accessors used to need. Deduction sees the **static** type of the expression, not the dynamic type, which is why `b.which()` deduces `Base&`. The patterns built on this, such as replacing the curiously recurring template pattern, belong to the topic on CRTP and deducing this.

A few rules keep the feature coherent. An explicit object member function cannot be `static`, `virtual`, or carry cv- or ref-qualifiers, since the parameter type already says all of that. The object parameter may be taken by value, written `this S self`, in which case a call copies or moves the object. And because the function has no hidden parameter left, taking its address gives a plain function pointer.

```cpp
#include <type_traits>

struct E {
  int v = 0;
  int get(this const E& self) { return self.v; }
};

static_assert(std::is_same_v<decltype(&E::get), int (*)(const E&)>);
// not int (E::*)() const: call it as (&E::get)(e)
```

Explicit object parameters also solve recursive lambdas: `[](this auto self, int n) { ... self(n - 1); }` names the closure object without `std::function` or a Y combinator.

## Static members

A static member function has no object parameter, so it has no `this`, cannot be `const` or ref-qualified, and cannot name non-static members without an object. You can still call it as `obj.f()`. For overload resolution, [over.match.funcs] gives it an implicit object parameter that accepts any object, which lets static and non-static overloads compete in one set. C++23 permits `static operator()` and `static operator[]`, so a stateless function object no longer passes an object pointer it never reads.

A static data member is one object shared by the class. Declared in the class without `inline`, it is only a declaration, and an odr-use needs a definition in exactly one translation unit. C++17 added `inline static` data members, which are definitions in the class body, and made every `static constexpr` data member implicitly inline.

```cpp
struct Limits {
  static constexpr int max = 64;   // definition: constexpr implies inline (C++17)
  static const int min = 0;        // declaration only: not inline
  inline static int calls = 0;     // definition (C++17)
};

const int& r = Limits::max;        // OK: odr-use, and a definition exists
// const int& s = Limits::min;     // odr-use with no definition anywhere:
//                                 // ill-formed, no diagnostic required (link error)
```

## Definitions in the class and the complete-class context

A member function defined inside its class definition is implicitly an inline function, per [class.mfct] and [dcl.inline]. That is what lets header-only classes appear in many translation units without violating the one definition rule. The exception is C++20 modules: a member function defined in a class that is attached to a named module is not implicitly inline.

Inside a class, some places are a **complete-class context**: function bodies, default arguments, `noexcept` specifiers and default member initializers. In those places the class is regarded as complete, so names declared later in the class are visible. Everywhere else in the class, ordinary top-to-bottom lookup applies, which bites in return types and parameter types.

```cpp
struct S {
  auto f() noexcept(noexcept(g())) { return g(); }  // OK: body and noexcept
  int g() noexcept { return 1; }                    //     see the later g
  // size_type h();      // error: return type is not a complete-class context
  using size_type = int;
};
```

> **Pitfall.** The fix for the commented line is to move the alias above its first use. Member type aliases are conventionally declared at the top of a class for exactly this reason.

## `this` in lambdas and default member initializers

`this` may appear in the body of an implicit object member function, in its trailing return type and `noexcept` specifier, and in default member initializers, where it points to the object being initialized. A member such as `Node* self = this;` is valid, and later members may read earlier ones, because members are initialized in declaration order.

A lambda in a member function reaches members through the captured `this` pointer. `[this]` captures the pointer, so the lambda refers to the original object and dangles if it outlives it. `[*this]`, added in C++17, copies the whole object into the closure. The default `[=]` used to capture `this` implicitly, which looked like a copy but was a pointer capture; C++20 deprecated that implicit capture, and `[=, this]` became the way to say it explicitly.

```cpp
#include <functional>

struct Counter {
  int n = 0;
  std::function<int()> by_pointer() { return [this]  { return n; }; }
  std::function<int()> by_copy()    { return [*this] { return n; }; }
  std::function<int()> legacy()     { return [=]     { return n; }; }
  // legacy: captures this, not *this; deprecated since C++20
};
```

An explicit object member function has no `this` to capture, so a lambda inside it must capture `self` by reference or by copy like any other parameter.

## What to remember

- A non-static member function has an object parameter; cv- and ref-qualifiers set its type, and overloading on them is ordinary overloading.
- Without a ref-qualifier, rvalues may bind to the implicit object parameter even when it is non-const.
- Inside a `&&`-qualified function, `*this` and named members are still lvalues; use `std::move(*this)`.
- C++23 explicit object parameters deduce from the static type of the object expression and leave no `this`; their address is an ordinary function pointer.
- Static member functions have no `this`; C++23 allows `static operator()` and `static operator[]`.
- `static constexpr` data members are implicitly inline since C++17; plain `static const` members are not.
- In-class member function definitions are implicitly inline, except when attached to a named module.
- Bodies, default arguments, `noexcept` specifiers and default member initializers see the whole class; return and parameter types do not.
- `[this]` captures a pointer, `[*this]` a copy, and implicit `this` capture through `[=]` is deprecated in C++20.

## Concept Map Outline

- **Member functions and this:** A non-static member function takes the object as one extra parameter.
  - **Implicit object parameter:** Overload resolution treats the object as an argument bound to a reference parameter.
    - **cv-qualifiers:** f() const gives the parameter type const X&, so const objects call only const overloads.
    - **Rvalue exception:** Without a ref-qualifier, an rvalue may bind to the non-const implicit object parameter.
    - **this:** A prvalue pointer to the cv-qualified class, pointing at the object parameter.
  - **Ref-qualifiers:** & and && make the object parameter an lvalue or rvalue reference (C++11).
    - **&& accessors:** Let rvalue objects give up their members, as optional::value() && does.
    - ***this stays lvalue:** Inside a && function, *this and named members are lvalues; use std::move(*this).
    - **No mixing:** A ref-qualified overload cannot coexist with an unqualified one for the same object type.
  - **Explicit object parameter:** C++23 deducing this: the object is the first parameter, written with this in front.
    - **No implicit this:** The body has no this pointer; members are reached as self.member.
    - **Static type deduction:** Self deduces from the static type of the object expression, never the dynamic type.
    - **Restrictions:** Cannot be static, virtual, or cv- or ref-qualified.
    - **Plain function pointer:** &S::f has type R(*)(S&...), not a pointer to member.
    - **Recursive lambdas:** [](this auto self, int n) can call self without std::function.
  - **Static members:** Belong to the class, with no object parameter and no this.
    - **Static member functions:** No this, no cv- or ref-qualifiers; still callable as obj.f().
    - **Static call operators:** C++23 allows static operator() and static operator[].
    - **Inline static data:** inline static members (C++17) are defined in the class body.
    - **constexpr implies inline:** static constexpr data members are inline since C++17; static const ones are not.
  - **Class body rules:** Where definitions live and what names they can see.
    - **In-class means inline:** Member functions defined in the class are inline, unless attached to a named module.
    - **Complete-class context:** Bodies, default arguments, noexcept and default member initializers see later members.
    - **Signatures see backwards:** Return and parameter types only see names declared earlier in the class.
  - **this in lambdas:** Lambdas reach members through a captured this.
    - **[this]:** Captures the pointer; the lambda dangles if it outlives the object.
    - **[*this]:** C++17: copies the whole object into the closure.
    - **[=] deprecation:** Implicit this capture through [=] is deprecated in C++20; write [=, this].

## Standardese Quiz Questions

### Question 1 [warmup] ([over.match.funcs], [over.ics.rank])

What does this program print?

```cpp
#include <cstdio>

struct S {
  void f()       { std::puts("plain"); }
  void f() const { std::puts("const"); }
};

void call(const S& s) { s.f(); }

int main() {
  S s;
  call(s);
  s.f();
}
```

A. `plain` then `plain`, because `s` itself is not const
B. `const` then `plain`
C. `const` then `const`
D. Ill-formed: the call through `const S&` is ambiguous

**Answer (B):** `const` then `plain`

**Why:** The object expression in `call` is an lvalue of type `const S`, which can only bind to the implicit object parameter `const S&`, so the const overload runs. In `main`, `s` is a non-const lvalue, and `S&` is a better match than `const S&`, so the plain overload runs. What matters is the type of the expression left of the dot, not the type the object was originally declared with.

### Question 2 [warmup] ([over.match.funcs], [class.temporary])

Is this program well-formed?

```cpp
struct S {
  int n = 0;
  void reset() { n = 0; }
};

int main() {
  S().reset();
}
```

A. Ill-formed: an rvalue cannot bind to the non-const implicit object parameter
B. Well-formed
C. Well-formed, but modifying a temporary is undefined behavior
D. Ill-formed: `reset` would need an `&&` ref-qualifier

**Answer (B):** Well-formed

**Why:** For a member function declared without a ref-qualifier, [over.match.funcs] makes an exception: an rvalue may bind to the implicit object parameter even though its type is a non-const lvalue reference. That is the rule the first option forgets. Modifying a temporary during its lifetime is perfectly defined; the temporary is simply destroyed at the end of the full-expression.

### Question 3 [warmup] ([class.static.data], [dcl.inline], [basic.def.odr])

In C++23, this is the whole program, in one translation unit. Is it well-formed?

```cpp
#include <cstdio>

struct Limits {
  static constexpr int max = 64;
};

int main() {
  const int& r = Limits::max;   // odr-uses Limits::max
  std::printf("%d\n", r);
}
```

A. Ill-formed, no diagnostic required: `max` needs a definition outside the class
B. Well-formed only if the compiler constant-folds `r`
C. Ill-formed: a reference cannot bind to a constexpr variable
D. Well-formed: the in-class declaration is a definition

**Answer (D):** Well-formed: the in-class declaration is a definition

**Why:** Since C++17 a `static constexpr` data member is implicitly an inline variable, so its in-class declaration is a definition and an odr-use such as binding a reference is fine. Before C++17 the first option was correct: binding the reference odr-used `max`, and without an out-of-class definition the program typically failed to link. A plain `static const int` member is still not inline today.

### Question 4 [tricky] ([expr.prim.id.unqual], [expr.prim.this], [over.match.funcs])

What does this program print?

```cpp
#include <cstdio>
#include <string>

struct Holder {
  std::string name = "x";
  static void sink(std::string&)  { std::puts("lvalue"); }
  static void sink(std::string&&) { std::puts("rvalue"); }
  void take() && { sink(name); }
};

int main() { Holder{}.take(); }
```

A. `lvalue`
B. `rvalue`, because `take` only runs on rvalues
C. Ill-formed: the call to `sink` is ambiguous
D. Unspecified: it depends on whether the temporary is materialized

**Answer (A):** `lvalue`

**Why:** The `&&` qualifier only decides which objects `take` may be called on. Inside the body, `name` is an id-expression naming a data member, which is an lvalue, exactly as in any other member function. To get `rvalue` you must write `sink(std::move(name))` or `sink(std::move(*this).name)`.

### Question 5 [tricky] ([class.mem], [basic.scope.class])

Which marked line makes this class definition ill-formed?

```cpp
struct S {
  auto f() noexcept(noexcept(g())) {  // A: noexcept names g
    return g();                        // B: body calls g
  }
  int g() noexcept { return 1; }
  size_type h();                       // C: return type
  using size_type = int;
};
```

A. A, because `g` is not declared yet
B. B, because `g` is not declared yet
C. C, because `size_type` is not declared yet
D. None of them; members are visible throughout the class

**Answer (C):** C, because `size_type` is not declared yet

**Why:** Function bodies, default arguments, `noexcept` specifiers and default member initializers are complete-class contexts, where the whole class is visible, so A and B find the later `g`. A member function's return type is not such a context, so `size_type` is looked up from that point backwards and is not found, so line C is ill-formed. Line A is the tempting answer, but the `noexcept` specifier was made a complete-class context precisely so it can refer to later members.

### Question 6 [tricky] ([dcl.fct], [temp.deduct.call])

What does this C++23 program print?

```cpp
#include <cstdio>
#include <type_traits>

struct Base {
  template <class Self>
  int which(this Self&&) {
    return std::is_same_v<std::remove_cvref_t<Self>, Base> ? 1 : 2;
  }
};
struct Derived : Base {};

int main() {
  Derived d;
  Base& b = d;
  std::printf("%d %d\n", d.which(), b.which());
}
```

A. `2 2`
B. `1 1`
C. Ill-formed: an explicit object parameter cannot be a forwarding reference
D. `2 1`

**Answer (D):** `2 1`

**Why:** `Self` is deduced at compile time from the object expression. `d` has type `Derived`, so `Self` is `Derived&`; `b` has static type `Base`, so `Self` is `Base&`, even though it refers to a `Derived`. Deducing `this` is not a virtual dispatch mechanism, which is why `2 2` is wrong. `this Self&&` is the canonical forwarding form of an explicit object parameter.

### Question 7 [standardese] ([expr.prim.lambda.capture], [depr.capture.this])

In C++20, what does the lambda capture, given that `n` is a non-static data member?

```cpp
struct Counter {
  int n = 0;
  auto get() { return [=] { return n; }; }
};
```

A. A copy of `n`
B. A copy of `*this`
C. The `this` pointer, and this implicit capture is deprecated
D. Nothing: the program is ill-formed because `this` is not listed

**Answer (C):** The `this` pointer, and this implicit capture is deprecated

**Why:** Naming `n` in the lambda means `(*this).n`, so what is implicitly captured is the entity `this`, and it is captured as a pointer even under a copy default. The closure therefore refers to the original object, which is why the first two options are tempting but wrong. C++20 deprecated implicitly capturing `this` through `[=]`; write `[=, this]` or `[*this]` to say which you mean.

### Question 8 [standardese] ([expr.unary.op], [dcl.fct])

In C++23, what is the type of `&E::get`?

```cpp
struct E {
  int v = 0;
  int get(this const E& self) { return self.v; }
};
```

A. `int (E::*)() const`
B. `int (*)(const E&)`
C. `int (E::*)(const E&)`
D. Ill-formed: the address of an explicit object member function cannot be taken

**Answer (B):** `int (*)(const E&)`

**Why:** For an explicit object member function, the object parameter is an ordinary parameter, and [expr.unary.op] says that taking its address yields a pointer to function, not a pointer to member. So the type is `int (*)(const E&)` and you call it as `(&E::get)(e)`. The pointer-to-member type in the first option is what you get for the classic spelling `int get() const`.
