Yes, you can take a function pointer to a static member function in C++. The syntax is similar to taking a pointer to a non-static member function, but with a few key differences.
Here's an example:
#include <iostream>
class MyClass {
public:
static void StaticFunc() {
std::cout << "Static function called\n";
}
void NonStaticFunc() {
std::cout << "Non-static function called\n";
}
};
int main() {
void (*StaticFuncPtr)() =
&MyClass::StaticFunc;
void (MyClass::*NonStaticFuncPtr)() =
&MyClass::NonStaticFunc;
StaticFuncPtr();
MyClass obj;
(obj.*NonStaticFuncPtr)();
}
Static function called
Non-static function called
Key points:
MyClass::
. It's just void (*)()
, same as a non-member function.MyClass::
, like void (MyClass::*)()
. This is because non-static member functions have an implicit this
 parameter, so the class type is part of the function type..*
 or >*
 operator to call the function on that instance.This difference arises because static member functions do not have access to an object instance (there's no this
pointer). They operate at the class level, not the object level. Non-static member functions, on the other hand, are always associated with an object instance.
Understanding these differences is important when using function pointers with class member functions. If you try to call a non-static member function pointer without an object instance, or if you try to call a static member function pointer with an object instance, you'll get a compilation error.
Answers to questions are automatically generated and may not have been reviewed.
Learn about first-class functions in C++: a feature that lets you store functions in variables, pass them to other functions, and return them, opening up new design possibilities