# Pointers to members

> A pointer to member names a member of a class without naming an object, and is applied to an object later with `.*` or `->*`. It converts along the inheritance hierarchy in the opposite direction from object pointers, and `std::invoke` turns it into an ordinary callable.

- **Source:** C++ Atlas (https://cppatlas.com/topics/pointers-to-members)
- **Track:** Classes
- **Estimated reading time:** 11 minutes
- **ISO C++ clauses:** [dcl.mptr] (https://eel.is/c++draft/dcl.mptr), [expr.unary.op] (https://eel.is/c++draft/expr.unary.op), [expr.mptr.oper] (https://eel.is/c++draft/expr.mptr.oper), [conv.mem] (https://eel.is/c++draft/conv.mem), [expr.static.cast] (https://eel.is/c++draft/expr.static.cast), [over.over] (https://eel.is/c++draft/over.over), [basic.compound] (https://eel.is/c++draft/basic.compound), [func.invoke] (https://eel.is/c++draft/func.invoke), [func.require] (https://eel.is/c++draft/func.require), [func.memfn] (https://eel.is/c++draft/func.memfn), [namespace.std] (https://eel.is/c++draft/namespace.std)
- **cppreference links:** [Pointer declaration (pointers to members)](https://en.cppreference.com/w/cpp/language/pointer), [Member access operators](https://en.cppreference.com/w/cpp/language/operator_member_access), [Address of an overloaded function](https://en.cppreference.com/w/cpp/language/overloaded_address), [std::invoke](https://en.cppreference.com/w/cpp/utility/functional/invoke), [std::mem_fn](https://en.cppreference.com/w/cpp/utility/functional/mem_fn)
- **Prerequisites:** member-functions-and-this, inheritance-and-virtual-functions

## The one idea

A pointer to member is a **path into an object**, not an address. `&S::m` means "the member `m` of whatever `S` you give me later". It does not point at memory, it cannot be converted to `void*`, and it becomes a real lvalue only when you combine it with an object using `.*` or `->*`.

Because it describes where a member sits inside a class, its conversions run the opposite way from object pointers. An `S*` converts to a pointer to its base. An `int Base::*` converts to `int Derived::*`, since every member of the base is also a member of the derived class.

> **Mental model.** An object pointer answers "which object?". A pointer to member answers "which part?", and needs an object before it means anything.

## Forming and applying them

The type is spelled with the class in front of the star: `int S::*` is a pointer to an `int` data member of `S`, and `int (S::*)(int) const` is a pointer to a `const` member function taking an `int`. It is formed only by `&` applied to a qualified name. Inside a member function, writing `&(S::m)` with parentheses, or plain `&m`, produces an ordinary `int*` to the member of `*this`.

```cpp
#include <cstdio>

struct S {
  int a = 1, b = 2;
  int twice(int x) const { return 2 * x; }
};

int main() {
  int S::* pm = &S::b;
  int (S::*pf)(int) const = &S::twice;
  S s;
  S* p = &s;
  std::printf("%d %d\n", s.*pm, (p->*pf)(pm == &S::b));   // 2 2
  pm = nullptr;                                         // null member pointer
}
```

The parentheses around `(p->*pf)` are required. `.*` and `->*` bind more loosely than a function call, so `s.*pf(1)` parses as `s.*(pf(1))` and is ill-formed.

The result of `.*` on a data member has the value category of the object: an lvalue object gives an lvalue, an rvalue object gives an xvalue. `->*` on a data member always gives an lvalue. For member functions, the ref-qualifiers apply: a `&&`-qualified function can only be called through an rvalue object. Applying a null pointer to member is undefined behavior.

Member pointers are values like any other. They can be compared with `==` and `!=`, where a null member pointer compares unequal to every pointer to an actual member, but `<` and the other relational operators do not apply to them. They can also be non-type template arguments, and they can sit in `constexpr` tables, which is how reflection-free serializers map field names to fields.

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

struct Config { int port; int threads; };

constexpr std::pair<const char*, int Config::*> fields[] = {
  {"port", &Config::port}, {"threads", &Config::threads}};

template<int Config::* M> int get(const Config& c) { return c.*M; }

void dump(const Config& c) {
  for (auto [name, m] : fields) std::printf("%s=%d\n", name, c.*m);
  std::printf("%d\n", get<&Config::threads>(c));
}
```

Static members are not reached through pointers to members. `&S::static_member` is an ordinary object or function pointer. Members of reference type and bit-fields cannot be pointed to at all. A C++23 explicit object member function behaves like a static one here: `&S::f` for `int f(this const S&)` has the type `int (*)(const S&)`, a topic covered in crtp-and-deducing-this.

## Conversions run the other way

[conv.mem] allows an implicit conversion from `T Base::*` to `T Derived::*`. Whatever `Base` member the pointer names, a `Derived` object contains it. The reverse direction needs `static_cast`, because the pointer might name a member that only some derived classes have.

```cpp
struct B { int x = 1; };
struct D : B { int y = 2; };

int D::* pd = &B::x;                          // OK: implicit, Base -> Derived
// int B::* bad = &D::y;                      // ill-formed: no implicit Derived -> Base
int B::* pb = static_cast<int B::*>(&D::y);   // OK, but only use it on a D

int read(B& b) { return b.*pb; }              // defined only if b is really a D
```

The rules have sharp edges that object pointers do not.

- The implicit conversion is ill-formed if `Base` is inaccessible, ambiguous, or a **virtual** base of `Derived`. A virtual base sits at a different offset in every most-derived class, so no fixed adjustment exists.
- `&D::x`, where `x` is declared in `B`, has type `int B::*`, not `int D::*`. The type records the class that declares the member, not the class you named.
- Using a pointer whose member is absent from the object's dynamic type is undefined behavior. [expr.mptr.oper] says so directly.

```cpp
#include <type_traits>
struct B { int x; void f(); };
struct D : B {};
static_assert(std::is_same_v<decltype(&D::x), int B::*>);
static_assert(std::is_same_v<decltype(&D::f), void (B::*)()>);
```

> **Pitfall.** Because `&D::f` has type `void (B::*)()`, template argument deduction sees `B`, not `D`. A template that deduces the class from a member pointer, such as `template<class C> void bind(void (C::*)())`, deduces `C = B` for `&D::f`.

## Virtual functions through member pointers

A pointer to a virtual member function keeps the virtual behaviour. Calling it through an object dispatches to the final overrider of the dynamic type, exactly like a call by name. There is no member pointer equivalent of the qualified call `b.B::f()`, which suppresses dispatch.

```cpp
#include <cstdio>
struct B { virtual void f() { std::puts("B::f"); } };
struct D : B { void f() override { std::puts("D::f"); } };

int main() {
  void (B::*pf)() = &B::f;
  D d;
  B* bp = &d;
  (bp->*pf)();   // D::f
  bp->B::f();    // B::f: only a qualified name turns dispatch off
}
```

## What they look like in memory

Nothing in this section is guaranteed by the standard. The sizes and encodings below are implementation practice, and code must not depend on them.

Under the Itanium C++ ABI, used by GCC and Clang on Linux and macOS, a pointer to data member is a single `ptrdiff_t` holding the byte offset of the member, and the null value is `-1`, because offset 0 is a valid member. A pointer to member function is two words: a function address or a virtual table offset, plus an adjustment added to `this`. That adjustment is what makes conversions across multiple inheritance work.

```text
Itanium ABI, 64-bit
  int S::*            [ offset (ptrdiff_t) ]          null = -1
  void (S::*)()       [ ptr | adj ]                   two words, 16 bytes
    x86-64:   virtual if ptr is odd, ptr = 1 + vtable offset
    AArch64:  virtual if adj is odd, ptr = vtable offset
```

On arm64 macOS, a pointer to the first virtual function measured as `ptr = 0, adj = 1` with both compilers, and a data member at offset 8 stored the value 8. MSVC is different again: the size of its member function pointers depends on the inheritance model, from a single code pointer for single inheritance to several fields for virtual inheritance or for a class that is still incomplete where the pointer type is used.

> **Standardese.** [basic.compound] lists pointers to members as their own compound type, separate from object and function pointers. [conv.mem] gives null member pointer values and the base-to-derived conversion; there is no conversion to or from `void*` or integers, and a `reinterpret_cast` between two member pointer types has an unspecified result except that casting back recovers the original.

## std::invoke, std::mem_fn and projections

Calling through a member pointer needs different syntax for an object, a pointer, a smart pointer, and a `std::reference_wrapper`. `std::invoke` hides all four behind one call, as specified by the INVOKE rules in [func.require] that [func.invoke] refers to. For a data member it returns a reference whose value category follows the object, so `std::invoke(&P::age, p) = 41;` assigns.

```cpp
#include <functional>
#include <memory>

struct P { int age; int older(int n) const { return age + n; } };

void demo(P& p, std::unique_ptr<P>& up) {
  std::invoke(&P::age, p) = 41;          // object: int&
  int a = std::invoke(&P::older, up, 1); // smart pointer: dereferenced with *
  int b = std::invoke(&P::age, &p);      // raw pointer
  auto m = std::mem_fn(&P::older);       // a function object wrapping INVOKE
  int c = m(std::ref(p), 2);             // reference_wrapper is unwrapped
  (void)a; (void)b; (void)c;
}
```

`std::mem_fn` packages the same behaviour as a reusable function object, which predates lambdas and is still handy as an argument. To pass a member function as a callback, C++20's `std::bind_front(&Widget::on_click, this)` binds the object as the first INVOKE argument. It stores `this` as a plain pointer, so the widget must outlive the callable; the member pointer does nothing to keep the object alive. For a single call site, a lambda that captures the object is usually clearer and lets the compiler see the target directly. The most common modern use is a **projection**. Ranges algorithms accept a projection that they apply through `std::invoke` before comparing, so a member pointer is enough to sort or search by a field.

```cpp
#include <algorithm>
#include <string>
#include <vector>

struct Person { std::string name; int age; };

void by_age(std::vector<Person>& v) {
  std::ranges::sort(v, {}, &Person::age);                   // compare ages
  auto it = std::ranges::find(v, 25, &Person::age);         // find age 25
  (void)it;
}
```

## Taking the address of an overloaded member

`&S::f` names an overload set if `f` is overloaded, and an overload set has no type. [over.over] resolves it from the target: the type of the variable being initialized, a parameter, or a cast. With `auto` or a deduced template parameter there is no target, and the expression is ill-formed.

```cpp
struct S {
  void f(int);
  void f(double);
};

void (S::*p)(int) = &S::f;                         // picks f(int)
auto q = static_cast<void (S::*)(double)>(&S::f);  // picks f(double)
// auto r = &S::f;                                 // ill-formed: no target type
```

Standard library members are a special case. [namespace.std] says forming a pointer to a non-static member function of a standard library class, such as `&std::string::size`, has unspecified behavior and may be ill-formed. Implementations are allowed to add overloads, default arguments, or extra template parameters to those members. Wrap the call in a lambda instead.

## What to remember

- `&S::m` with a qualified name forms a pointer to member; `&(S::m)` does not.
- Write `(obj.*pmf)(args)` and `(ptr->*pmf)(args)`; the parentheses are required.
- `T Base::*` converts implicitly to `T Derived::*`; the other direction needs `static_cast` and a matching dynamic type.
- No implicit conversion goes through an inaccessible, ambiguous or virtual base.
- `&Derived::inherited` has the type of the declaring class, `T Base::*`.
- Member function pointers to virtual functions still dispatch virtually.
- Sizes and encodings are ABI choices: on Itanium, an offset with null `-1`, and a two-word pair for functions.
- `std::invoke` and `std::mem_fn` make member pointers callable with objects, pointers, smart pointers and `std::ref`; ranges projections use them.
- Overloaded members need a target type; never take the address of a standard library member function.

## Concept Map Outline

- **Pointers to members:** A path to a member of some class, applied to an object later with .* or ->*.
  - **Forming and applying:** &S::m with a qualified name, used as obj.*pm or ptr->*pm.
    - **Qualified name only:** &(S::m) or &m inside a member gives an ordinary pointer to this object's member.
    - **Call parentheses:** Write (obj.*pmf)(args); obj.*pmf(args) parses as obj.*(pmf(args)).
    - **Value category:** obj.*pm is an lvalue for an lvalue object and an xvalue for an rvalue object.
    - **Not pointable:** Static members give plain pointers; reference members and bit-fields cannot be pointed to.
  - **Conversions:** They run from base to derived, the reverse of object pointers.
    - **Base to derived:** T B::* converts implicitly to T D::* because D contains every member of B.
    - **Derived to base:** Needs static_cast; using it on an object lacking the member is undefined behavior.
    - **Forbidden bases:** No conversion through an inaccessible, ambiguous or virtual base.
    - **Declaring class type:** &D::x for a member of B has type int B::*.
  - **Virtual functions:** A pointer to a virtual function dispatches on the dynamic type when called.
    - **No non-virtual form:** Only a qualified call like b.B::f() suppresses dispatch; member pointers cannot.
  - **Representation:** Implementation practice only; the standard fixes no size or layout.
    - **Itanium data pointer:** One ptrdiff_t holding the member offset, with -1 as the null value.
    - **Itanium function pointer:** Two words: function address or vtable offset, plus a this adjustment.
    - **Virtual flag:** Low bit of ptr on x86-64, low bit of adj on AArch64 including arm64 macOS.
    - **MSVC:** Size depends on the inheritance model of the class.
  - **invoke and projections:** Library wrappers make member pointers ordinary callables.
    - **std::invoke:** Accepts objects, pointers, smart pointers and reference_wrapper; data members return references.
    - **std::mem_fn:** Wraps a member pointer in a reusable function object.
    - **Projections:** ranges::sort(v, {}, &P::age) compares by a field through std::invoke.
  - **Overloaded members:** An overload set has no type, so the target type selects the member.
    - **Target type:** A typed variable, parameter or static_cast picks the overload; auto cannot.
    - **Library members:** Forming &std::string::size is unspecified and possibly ill-formed; use a lambda.
    - **Explicit object (C++23):** &S::f for f(this const S&) is an ordinary function pointer.

## Standardese Quiz Questions

### Question 1 [warmup] ([expr.mptr.oper], [expr.call])

Is the initialization of `r` well-formed?

```cpp
struct S { int f() { return 1; } };

int main() {
  S s;
  int (S::*pf)() = &S::f;
  int r = s.*pf();
  return r;
}
```

A. Well-formed: it calls `s.f()` and `r` is 1
B. Ill-formed: it parses as `s.*(pf())`, and `pf` cannot be called on its own
C. Well-formed, but it is undefined behavior because `pf` is called without an object
D. Ill-formed: `.*` cannot be used with member functions, only `->*`

**Answer (B):** Ill-formed: it parses as `s.*(pf())`, and `pf` cannot be called on its own

**Why:** The pointer-to-member operators bind more loosely than the function call postfix operator, so `s.*pf()` means `s.*(pf())`. A pointer to member function is not callable by itself, and both GCC and Clang reject the call. The correct spelling is `(s.*pf)()`. Both `.*` and `->*` work with member function pointers; `->*` is for a pointer to the object.

### Question 2 [warmup] ([expr.mptr.oper], [class.virtual], [expr.call])

What does this program print?

```cpp
#include <cstdio>

struct B { virtual void f() { std::puts("B::f"); } };
struct D : B { void f() override { std::puts("D::f"); } };

int main() {
  void (B::*pf)() = &B::f;
  D d;
  B* bp = &d;
  (bp->*pf)();
}
```

A. `D::f`
B. `B::f`, because the pointer was formed from `&B::f`
C. Unspecified: it depends on how the ABI encodes virtual member pointers
D. Nothing: it is ill-formed to take the address of a virtual function

**Answer (A):** `D::f`

**Why:** A pointer to a virtual member function designates the virtual function, not one particular definition. Calling it through an object performs the same dispatch as `bp->f()`, so the final overrider for the dynamic type `D` runs. Naming `B::f` in `&B::f` only forms the pointer; only a qualified call such as `bp->B::f()` suppresses dispatch. The ABI encoding differs between platforms, but the behaviour is specified.

### Question 3 [warmup] ([conv.mem], [expr.static.cast])

Which declaration is ill-formed?

```cpp
struct B { int x; };
struct D : B { int y; };

int D::* p1 = &B::x;                       // #1
int B::* p2 = &D::y;                       // #2
int B::* p3 = static_cast<int B::*>(&D::y); // #3
```

A. #1 only
B. #1 and #3
C. #2 only
D. None

**Answer (C):** #2 only

**Why:** Pointers to members convert in the opposite direction from object pointers. Every member of `B` is a member of `D`, so `int B::*` converts implicitly to `int D::*`, which makes #1 fine. `y` exists only in `D`, so going from `int D::*` to `int B::*` needs a `static_cast`; #3 is well-formed and #2 is ill-formed. Using `p3` on an object that is not really a `D` would be undefined behavior.

### Question 4 [tricky] ([expr.unary.op], [conv.mem])

What is `decltype(&D::x)`?

```cpp
struct B { int x; };
struct D : B {};
```

A. `int D::*`
B. `int*`
C. Ill-formed: `x` is not declared in `D`
D. `int B::*`

**Answer (D):** `int B::*`

**Why:** When `&` is applied to a qualified name of a non-static member, the result's class is the class in which the member is declared, not the class named in the qualifier. So `&D::x` has type `int B::*`, which then converts implicitly to `int D::*` if needed. The difference shows up in template argument deduction, where a parameter `int C::*` deduces `C = B`.

### Question 5 [tricky] ([conv.mem])

Is this declaration well-formed?

```cpp
struct V { int v; };
struct D : virtual V {};

int D::* p = &V::v;
```

A. Well-formed: base-to-derived member pointer conversion is always implicit
B. Ill-formed: the conversion goes through a virtual base
C. Well-formed, but using `p` is undefined behavior
D. Ill-formed: `V` is an inaccessible base

**Answer (B):** Ill-formed: the conversion goes through a virtual base

**Why:** [conv.mem] forbids the conversion from `T B::*` to `T D::*` when `B` is inaccessible, ambiguous, or a virtual base of `D`. A virtual base can sit at a different offset in each most-derived object, so the pointer could not be adjusted by a fixed amount. The base here is public, so the fourth option names the wrong reason; with a non-virtual base the first option would be right.

### Question 6 [tricky] ([func.invoke], [func.require], [expr.mptr.oper])

Given `struct P { int age; }; P p;`, what is `decltype(std::invoke(&P::age, std::move(p)))`?

A. `int`
B. `int&`
C. `int&&`
D. `const int&`

**Answer (C):** `int&&`

**Why:** For a pointer to data member, INVOKE is `t1.*f` when `t1` is an object, and `.*` on a data member gives an xvalue when the object is an xvalue. `std::invoke` returns that expression's type, so the result is `int&&`. With the lvalue `p` it would be `int&`, which is the tempting answer. It is never a copy, so `int` is wrong too, and no `const` is added.

### Question 7 [standardese] ([expr.mptr.oper], [expr.static.cast])

What does the standard say about evaluating `f()`?

```cpp
struct B { int b = 0; };
struct D1 : B { int d1 = 1; };
struct D2 : B { int d2 = 2; };

int f() {
  int B::* p = static_cast<int B::*>(&D1::d1);
  D2 d;
  B& br = d;
  return br.*p;
}
```

A. Undefined behavior
B. It returns 1
C. Ill-formed: the `static_cast` from `int D1::*` is not allowed
D. It returns 2, because `d1` and `d2` have the same offset

**Answer (A):** Undefined behavior

**Why:** The `static_cast` is valid because `B` is a non-virtual, accessible base of `D1`. But [expr.mptr.oper] says that if the dynamic type of the object does not contain the member the pointer refers to, the behavior is undefined. The dynamic type here is `D2`, which has no `d1`. On common ABIs the offset happens to land on `d2`, which is why the last option can appear to work, but that is not a result the standard gives.

### Question 8 [standardese] ([namespace.std], [member.functions])

What does the C++23 standard say about this declaration?

```cpp
#include <string>

auto p = &std::string::size;
```

A. It is well-formed and portable: `size` is a public member function
B. It is ill-formed: library member functions are always overloaded
C. Its behavior is unspecified, and it may be ill-formed
D. It is undefined behavior only if `p` is called

**Answer (C):** Its behavior is unspecified, and it may be ill-formed

**Why:** [namespace.std] says that forming a pointer to member designating a standard library non-static member function makes the behavior of the program unspecified, possibly ill-formed. Implementations may add overloads, default arguments or extra parameters to library members, so the address need not mean the same thing everywhere. GCC and Clang accept it today, which is why the first option is tempting. Use a lambda such as `[](const std::string& s) { return s.size(); }` instead.
