skip to content

In C++, how do you call a member function through a member function pointer, and what does std::invoke add?

level: middleimportance: should knowfreq 45%

answer

  1. the class is part of the type
  2. .* and ->* need parentheses
  3. objects, pointers and reference_wrapper
  4. one call syntax for generic code

basics

~10 s

A member function pointer such as void (Scheduler::*)(int) needs an object: call it with (obj.*p)(1) or (ptr->*p)(1). C++17's std::invoke(p, obj, 1) gives one syntax for every callable, including member pointers.

solid answer

~40 s

A **pointer to member function** names a member of a class, not a location: `void (Scheduler::*p)(int) = &Scheduler::run;` (the `&` and the class qualification are required). It has no object, so you supply one at the call: `(s.*p)(1)` for an object or reference, `(ptr->*p)(1)` for a pointer. The parentheses matter, because `s.*p(1)` parses as `s.*(p(1))` and fails. A **pointer to data member**, `int Scheduler::*`, works the same way. `std::invoke` (C++17) unifies all of this: `std::invoke(f, args...)` calls a function, a function object, or a member pointer with the object as the first argument, whether that is an object, a raw pointer, a `std::reference_wrapper` or a smart pointer. Generic code, such as a scheduler that accepts any callable, uses it so that member pointers work too.

code

cpp · 27 lines
cpp
#include <cstdio>
#include <functional>
#include <memory>

struct Scheduler {
  int runs = 0;
  void run(int job_id) { ++runs; std::printf("run job %d\n", job_id); }
  int priority = 3;
};

int main() {
  void (Scheduler::*run_ptr)(int) = &Scheduler::run;  // member function pointer
  int Scheduler::*prio_ptr = &Scheduler::priority;     // pointer to data member

  Scheduler s;
  auto owner = std::make_unique<Scheduler>();
  (s.*run_ptr)(1);                 // object: .*  (parentheses required)
  (owner.get()->*run_ptr)(2);      // raw pointer: ->*

  std::invoke(run_ptr, s, 3);          // C++17: one syntax for all of them
  std::invoke(run_ptr, &s, 4);
  std::invoke(run_ptr, std::ref(s), 5);
  std::invoke(run_ptr, owner, 6);      // unique_ptr: dereferenced for you
  std::printf("priority=%d runs=%d\n", std::invoke(prio_ptr, s), s.runs);
  std::printf("sizeof member fn ptr=%zu, sizeof fn ptr=%zu\n", sizeof run_ptr,
              sizeof(void (*)(int)));
}

go deeper

for a junior

Recognise the member function pointer syntax and that a non-static member needs an object to be called.

for a middle

Explain .* and ->*, why the parentheses are required, and the INVOKE rules that let std::invoke accept objects, pointers, reference wrappers and smart pointers.

for a senior

Use std::invoke and std::is_invocable in generic callback code so member pointers work, and know that member pointer layout is an ABI detail.

for a principal

Decide whether a callback API should accept member pointers directly or require callers to wrap them, weighing convenience against a simpler contract.

## What a member function pointer is A non-static member function cannot run without an object, so a pointer to one cannot be an ordinary function pointer. The type carries the class: `void (Scheduler::*)(int)` is "pointer to a member function of `Scheduler` taking `int` and returning `void`". You form one only with `&` and a qualified name, `&Scheduler::run`; unlike a free function, a member function name does not decay to a pointer on its own. A **pointer to data member**, such as `int Scheduler::*prio = &Scheduler::priority;`, is the data counterpart: given an object it selects that field. The representation is the implementation's business. On this Apple arm64 build with Clang, the code example printed `sizeof member fn ptr=16` against 8 for a plain function pointer: that ABI stores extra information so that a pointer to a virtual function, or one used through a base class, still dispatches correctly. Other ABIs choose other sizes. ## Calling through one | Have | Syntax | Note | |---|---|---| | object or reference `s` | `(s.*p)(1)` | `.*` binds the member to the object | | pointer `ptr` | `(ptr->*p)(1)` | `->*` dereferences first | | smart pointer `owner` | `((*owner).*p)(1)` or `(owner.get()->*p)(1)` | `->*` is not overloaded by `std::unique_ptr` | | data member pointer `prio` | `s.*prio` | yields the field as an lvalue | The parentheses around `s.*p` are mandatory. The function call operator binds tighter than `.*`, so `s.*p(1)` tries to call `p` itself; Clang reports `called object type 'void (Scheduler::*)(int)' is not a function or function pointer`. ## What std::invoke adds The standard defines a single calling convention, **INVOKE**, used throughout the library, and C++17 exposes it as `std::invoke` in `<functional>`. `std::invoke(f, t1, args...)`: 1. calls `(t1.*f)(args...)` when `f` is a pointer to member function and `t1` is an object of that class or a derived class; 2. calls `(t1.get().*f)(args...)` when `t1` is a `std::reference_wrapper`; 3. calls `((*t1).*f)(args...)` otherwise, which covers raw pointers and smart pointers such as `std::unique_ptr`; 4. reads `t1.*f` (or the same through `get()` or `*`) when `f` is a pointer to data member and there are no further arguments; 5. calls `f(t1, args...)` for everything else: functions, function pointers, lambdas and other function objects. The code example calls `run` five ways, through an object, a raw pointer, a `std::reference_wrapper` and a `std::unique_ptr`, and reads `priority` through a data member pointer, all with the same `std::invoke` spelling. ## Why generic code cares A job scheduler that accepts "anything callable" should not force teams to wrap a member function in a lambda. Writing `std::invoke(job, args...)` instead of `job(args...)` makes member pointers work as well: `scheduler.submit(&Cache::flush, &cache)` becomes possible. `std::function`, `std::bind` and the C++20 ranges algorithms already call their targets through INVOKE, which is why a `std::function<void(Cache&)>` can hold `&Cache::flush`. The traits `std::is_invocable_v` and `std::invoke_result_t` describe the same rules for constraints and return types. A minimal version of that scheduler, compiled as C++17: ```cpp class Scheduler { public: template <class F, class... Args> void submit(F&& f, Args&&... args) { static_assert(std::is_invocable_v<F&, Args&...>, "job is not callable with these arguments"); std::invoke(f, args...); // a real scheduler would store the job and run it later } }; // s.submit(&Cache::flush, &cache, 2); member function, object pointer // s.submit([](int n) { /* ... */ }, 3); lambda ``` Both calls compile and run through the same `std::invoke` line; a plain `f(args...)` would reject the first one. ## Mistakes interviewers listen for - Expecting `&Scheduler::run` to convert to `void (*)(int)`. Only a `static` member function does. - Dropping the parentheses in `(s.*p)(1)`. - Assuming a member function pointer is the size of an address. - Writing a generic wrapper that calls `f(args...)` and so rejects member pointers, where `std::invoke` would accept them. - Thinking `std::invoke` adds run-time cost of its own; it is a function template that resolves the call form at compile time.

  • Does calling a virtual member function through a member function pointer dispatch virtually?
    Yes. A pointer to a virtual member function, such as `&Base::run`, called on a `Derived` object through a `Base&` runs the override in `Derived`. That is part of why the representation is more than a plain address on common ABIs: it must record enough to look up the right function at the call.
  • Why can a static member function's address be stored in a plain function pointer?
    A `static` member function has no `this` and needs no object, so `&Scheduler::make_default` has an ordinary function type such as `Scheduler (*)()`. Only non-static members produce pointer-to-member types with the class in them.

  • &Scheduler::run converts to an ordinary void (*)(int) function pointer.
  • s.*p(1) calls the member function on s without extra parentheses.
  • A member function pointer is always the same size as a data pointer.
  • std::invoke cannot call member pointers through a std::unique_ptr.
  • std::invoke adds a run-time dispatch layer compared with a direct call.