Function Pointers and Const

How does const-correctness apply to function pointers? Can I have a pointer to a const function?

Const-correctness is an important concept in C++, and it also applies to function pointers. You can have pointers to const functions, which can be useful in ensuring that the pointed-to function does not modify the state of the object it is called on. Here's an example:

#include <iostream>

class Player {
 public:
  bool isAlive() const { return mAlive; }
  void setAlive(bool Alive) { mAlive = Alive; }

 private:
  bool mAlive{true};
};

int main() {
  bool (Player::*isAlivePtr)() const {
    &Player::isAlive};  

  const Player MyPlayer;
  std::cout << std::boolalpha;
  std::cout << (MyPlayer.*isAlivePtr)() << '\n';
}
true

In this example, isAlivePtr is a pointer to a const member function of the Player class. The const-qualifier is added after the function's parameter list in the pointer type: bool (Player::*)() const.

When declaring the pointer, we take the address of the isAlive member function, which is marked as const. This ensures that the pointed-to function does not modify the object's state.

If we try to assign a non-const member function to a const function pointer, like uncommenting the line with the error comment, we will get a compilation error:

error: cannot convert from 'bool (Player::*)()' to 'bool (Player::*)() const'

This helps maintain const-correctness and prevents inadvertent modifications of const objects through function pointers.

Const function pointers are particularly useful when working with const objects, as they ensure that only const member functions can be called on those objects, maintaining the integrity of the const-correctness.

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?
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?
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 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