Function Pointers

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?

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved