Pointers to Member Functions

Is it possible to create a pointer to a member function of a class? If so, how is it different from a regular function pointer?

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:

  1. The type of the member function pointer includes the class name and the scope resolution operator ::. In this case, it's bool (Player::*)() const.
  2. When assigning the address of the member function, we use the & operator followed by the class name and the scope resolution operator, like &Player::isAlive.
  3. To call a member function through its pointer, we need an instance of the class. We use the .* 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.

Function Pointers

Learn about function pointers: what they are, how to declare them, and their use in making our code more flexible

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Storing Function Pointers
How can I store multiple function pointers of the same type in a collection like a vector or array?
Capturing this in Lambdas
How can I use a lambda to create a function pointer that calls a member function of my class?
Function Pointers and Const
How does const-correctness apply to function pointers? Can I have a pointer to a const function?
Function Pointers and Inheritance
Can I assign a derived class member function to a base class function pointer? How does inheritance affect function pointers?
Using Function Pointers with STL Algorithms
Can I use function pointers with STL algorithms like std::find_if or std::sort? How can I pass a function pointer as a predicate or comparison function?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant