Yes, it is possible to create pointers to member functions in C++. The syntax is slightly different compared to regular function pointers. Here's an example:
#include <iostream>
class Player {
public:
bool isAlive() const { return true; }
};
int main() {
bool (Player::*isAlivePtr)() const {
&Player::isAlive};
Player MyPlayer;
std::cout << std::boolalpha;
std::cout << (MyPlayer.*isAlivePtr)() << '\n';
}
true
The key differences are:
::
. In this case, it's bool (Player::*)() const
.&
 operator followed by the class name and the scope resolution operator, like &Player::isAlive
..*
 operator instead of the  operator, followed by the instance and the member function pointer, like (MyPlayer.*isAlivePtr)()
.It's important to note that member function pointers can only be called on instances of the class they belong to. They also have access to the class's this
pointer and can modify the object's state (unless the function is marked as const
).
Member function pointers are useful in situations where you need to store or pass references to specific member functions of a class, similar to how regular function pointers can be used for free functions.
Answers to questions are automatically generated and may not have been reviewed.
Learn about function pointers: what they are, how to declare them, and their use in making our code more flexible