Function Pointers

Function Pointers and Const

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

Abstract art representing computer programming

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.

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:

  • 125 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