Const Member Function Pointers
How can we handle member function pointers for const member functions?
Handling member function pointers for const member functions in C++ is similar to handling regular member function pointers, but with a few important distinctions. Here's how you can work with const member function pointers:
Declaration Syntax
When declaring a pointer to a const member function, you need to include the const keyword in the declaration:
class MyClass {
public:
int getValue() const { return value; }
private:
int value = 42;
};
// Pointer to const member function
int (MyClass::*constMemberPtr)() const =
&MyClass::getValue;Using std::mem_fn()
std::mem_fn() works seamlessly with const member functions, automatically deducing the constness:
auto getter = std::mem_fn(&MyClass::getValue);
const MyClass obj;
std::cout << getter(obj); // Outputs: 42Function Objects and std::function
When using std::function to store a const member function pointer, you need to specify the constness in the function signature:
std::function<int(const MyClass&)> func =
&MyClass::getValue;Calling const Member Function Pointers
When calling a const member function pointer, you need to use a const object or a pointer/reference to a const object:
#include <iostream>
class Rectangle {
public:
int getArea() const { return width * height; }
int width = 5, height = 3;
};
int main() {
int (Rectangle::*areaPtr)() const =
&Rectangle::getArea;
const Rectangle r;
std::cout << (r.*areaPtr)() << '\n';
const Rectangle* pr = &r;
std::cout << (pr->*areaPtr)();
}15
15Template Functions
When writing template functions that can work with both const and non-const member functions, you can use auto to deduce the constness:
template <typename Class, typename Func>
auto callMember(
const Class& obj, Func Class::*memberFunc
) {
return (obj.*memberFunc)();
}
int main() {
const Rectangle r;
// Outputs: 15
std::cout << callMember(r, &Rectangle::getArea);
}Overloading and const
Remember that C++ allows overloading based on constness. If a class has both const and non-const versions of a member function, you need to be explicit about which one you're pointing to:
#include <iostream>
class OverloadedClass {
public:
int getValue() { return 1; }
int getValue() const { return 2; }
};
int main() {
int (OverloadedClass::*nonConstPtr)() =
&OverloadedClass::getValue;
int (OverloadedClass::*constPtr)() const =
&OverloadedClass::getValue;
OverloadedClass obj;
const OverloadedClass constObj;
std::cout << (obj.*nonConstPtr)() << '\n';
std::cout << (constObj.*constPtr)();
}1
2By understanding these nuances, you can effectively work with const member function pointers in C++, maintaining const-correctness and leveraging the full power of C++'s type system.
Member Function Pointers and Binding
Explore advanced techniques for working with class member functions