How Do I Invoke a Member Function Pointer in C++?

Via std::invoke: (since C++17)

#include <functional>

std::invoke(memberFunctionPtr, myObject, parameters);

On an object:

(myObject.*memberFunctionPtr)(parameters);

On a pointer to an object:

(myObjectPtr->*memberFunctionPtr)(parameters);


How Do I Declare a Member Function Pointer in C++?

Ideally, use a type alias: (since C++11)

using typeName = returnType (className::*)(parameterTypes);

...or a typedef:

typedef returnType (className::*typeName)(parameterTypes);

...and then use it like a regular type:

As a variable:

typeName variableName = &className::function_name;

As an array:

typeName arrayName[] = { &className::function_name0, ... };

As a parameter to a function:

int my_function(typeName parameterName);

As a return value from a function:

typeName my_function(int, ...);


What About The Verbose Syntax?

Please reconsider, but if you must...

As a variable:

returnType (className::*variableName)(parameterTypes) = &className::function_name;

As an array:

returnType (className::*arrayName[])(parameterTypes) = { &className::function_name0, ... };

As a parameter to a function:

int my_function(returnType (className::*parameterName)(parameterTypes));

As a return value from a function: (with trailing return types, since C++11)

auto my_function(int, ...) -> auto (className::*)(parameterTypes) -> returnType;

As a return value from a function: (without trailing return types, or prior to C++11)

returnType (className::*my_function(int, ...))(parameterTypes);
This site is not intended to be an exhaustive list of all possible uses of pointers to member functions.
It is highly recommended to use a type alias or typedef for the sake of readability.

Unable to access this site due to the profanity in the URL? https://goshdarnmemberfunctionpointers.com is a more work-friendly mirror.