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