Pointers to Class Member#
Summary based on C++ Primer, 5th ed. Section 19.4: Pointers to Class Member, paired with modern C++ std::invoke and C++20 Ranges projections.
1. Ordinary Pointers vs. Pointers to Class Member (.*, ->*)#
While an ordinary pointer TYPE* stores the actual memory address of a specific live object, a pointer to member TYPE CLASS::* stores no object address at all — it identifies which non-static member within CLASS to select, such as its relative byte offset inside CLASS.
| Aspect | Ordinary Pointer TYPE* | Pointer to Member TYPE CLASS::* |
|---|---|---|
| Target | Actual address of a specific object in memory | Relative member slot within CLASS, independent of any instance |
| Initialization | &CLASS_INSTANCE.MEMBER | &CLASS::MEMBER |
| Standalone Dereference | ✅ *PTR | ❌ Must bind to an object or pointer — CLASS_INSTANCE.*MEMBER_PTR, CLASS_PTR->*MEMBER_PTR |
static Members | ✅ static members belong to no instance, so use TYPE* | ❌ Non-static members only |
- Overloadability:
.and.*operate directly on objects and cannot be overloaded in C++, whereas their pointer counterparts->and->*can be overloaded for smart pointers and iterators — see Overloaded Operations.
2. Syntax for Data Members and Member Functions#
1. Pointers to Data Members#
Prepend CLASS:: before * to specify the class type, or use auto when initializing directly:
struct Point {
int x;
int y;
};
// Equivalent to: int Point::* mp = &Point::x;
auto mp = &Point::x;
Point p1{1, 2};
Point* ptr = &p1;
int a = p1.*mp; // Use .* on an object -> p1.x (1)
int b = ptr->*mp; // Use ->* on a pointer -> ptr->x (1)
mp = &Point::y; // Retarget to member y
int c = p1.*mp; // p1.y (2)
2. Pointers to Member Functions & Precedence Rule#
A pointer to member function must match the parameter types and qualifiers (const, noexcept) of the target function. Because the call operator () has higher precedence than .* and ->*, you must parenthesize (CLASS_INSTANCE.*FUNC_PTR)(ARGS...) and (CLASS_PTR->*FUNC_PTR)(ARGS...):
class Screen {
public:
char get() const { return 'A'; }
char get(int r, int c) const { return 'B'; }
};
// Explicit type selects the two-parameter overload, including const
char (Screen::*fp)(int, int) const = &Screen::get;
Screen s;
Screen* sp = &s;
// char c = s.*fp(0, 0); // ❌ Compile error: parsed as s.*(fp(0, 0))!
char c1 = (s.*fp)(0, 0); // ✅ Bind to object first, then invoke
char c2 = (sp->*fp)(0, 0); // ✅ Bind to pointer first, then invoke
3. When Are They Used?#
You rarely type .* or ->* directly in application code, but passing &CLASS::MEMBER to standard library utilities is very common — the library performs the underlying .* / ->* dereference via std::invoke.
1. C++17 std::invoke and std::mem_fn#
std::invoke(<functional>): Calls ordinary functions, lambdas, data member pointers, and member function pointers throughstd::invoke(CALLABLE, ARGS...), inspectingCALLABLEat compile time to splitARGS...differently:- For an ordinary function or lambda (no
thisinstance), all ofARGS...are forwarded directly as function arguments. - For a non-
staticmember pointer, the first argument inARGS...(obj) is consumed as the target object (this), and any remaining arguments are forwarded as the member function’s parameters.std::invokealso automatically handles values/references, raw/smart pointers, andstd::reference_wrapper:
- For an ordinary function or lambda (no
CALLABLE Kind | std::invoke Form | How ARGS... Is Split & Evaluated |
|---|---|---|
| Function / Lambda / Functor | std::invoke(fn, a, b) | All args are parameters → fn(a, b) |
Member Function Pointer (&C::Method) | std::invoke(&C::Method, obj, a, b) | 1st arg obj = target instance (this), rest a, b = parameters:• Object/ref: (obj.*(&C::Method))(a, b)• Pointer / smart pointer: ((*obj).*(&C::Method))(a, b)• std::ref(x): (obj.get().*(&C::Method))(a, b) |
Data Member Pointer (&C::field) | std::invoke(&C::field, obj) | Only 1 target arg obj allowed (returns member reference):• Object/ref: obj.*(&C::field)• Pointer / smart pointer: (*obj).*(&C::field) |
This lets generic library templates (std::ranges, std::thread, std::apply) accept lambdas, member functions, and struct fields interchangeably with a single std::invoke call instead of writing separate overloads.
std::mem_fn(<functional>): A raw member pointer has nooperator(), so C++11<algorithm>utilities cannot call it directly. Wrapping it withstd::mem_fn(&CLASS::MEMBER)produces a callable functor whose first parameter is the target object or pointer (forwarding internally tostd::invoke):
#include <algorithm>
#include <functional>
#include <memory>
#include <string>
#include <vector>
struct Box {
int Scale(int factor) const { return val * factor; }
int val = 10;
};
Box b;
auto bp = std::make_unique<Box>(Box{20});
// 1) Ordinary lambda: all of ARGS (10, 3) are function parameters
int r1 = std::invoke([](int x, int y) { return x * y; }, 10, 3); // -> 30
// 2) Member function pointer: 1st arg (b, &b, bp) is the target object (this), 2nd arg (3) is Scale(factor)
int r2 = std::invoke(&Box::Scale, b, 3); // (b.*(&Box::Scale))(3) -> 30
int r3 = std::invoke(&Box::Scale, &b, 3); // ((&b)->*(&Box::Scale))(3) -> 30
int r4 = std::invoke(&Box::Scale, bp, 3); // ((*bp).*(&Box::Scale))(3) -> 60 (smart pointers dereferenced too)
// 3) Data member pointer: takes only the target object (b) and returns int& (extra args fail to compile)
int& v = std::invoke(&Box::val, b); // b.*(&Box::val) -> 10
v = 15; // b.val == 15
std::vector<std::string> words = {"hello", "", "world"};
// Wrap member function pointer into a callable functor for C++11 <algorithm>
auto it = std::find_if(words.begin(), words.end(), std::mem_fn(&std::string::empty));2. C++20 Ranges Projections (std::ranges::sort, etc.)#
The most common place you see &CLASS::MEMBER in modern C++. Instead of writing a verbose comparator lambda just to sort or search by one struct field, pass the member pointer as the projection argument:
#include <algorithm>
#include <string>
#include <vector>
struct User {
std::string name;
int age;
};
std::vector<User> users = {{"Alice", 30}, {"Bob", 20}};
// 2nd arg {} uses the default comparator (std::ranges::less{}, ascending); 3rd arg &User::age is the projection
std::ranges::sort(users, {}, &User::age);
// Equivalent lambda forms for comparison:
// 1) Unary projection lambda as the 3rd argument:
// std::ranges::sort(users, {}, [](const User& u) { return u.age; });
// 2) Binary comparator lambda as the 2nd argument (3rd projection omitted):
// std::ranges::sort(users, [](const User& a, const User& b) { return a.age < b.age; });
3. std::thread Callbacks and Command Dispatch Tables#
- Launching
std::threadon a member function: Pass&Worker::Runfollowed by the target object pointer&wand arguments. - Command dispatch tables (C++ Primer 19.4 idiom): Map enum/integer indices directly to an array of member function pointers without
if-elsechains.
#include <thread>
struct Worker {
void Run(int id) {}
};
Worker w;
std::thread t(&Worker::Run, &w, 1); // Internally executes (&w ->* &Worker::Run)(1)
t.join();
// Command dispatch table example
class Cursor {
public:
Cursor& up() { return *this; }
Cursor& down() { return *this; }
enum Direction { UP, DOWN };
Cursor& Move(Direction dir) {
return (this->*kMenu[dir])(); // Dispatch directly by index without branching
}
private:
using Action = Cursor& (Cursor::*)();
static constexpr Action kMenu[] = {&Cursor::up, &Cursor::down};
};