C++ Pointers to members Pointers to static member functions


Example

A static member function is just like an ordinary C/C++ function, except with scope:

  • It is inside a class, so it needs its name decorated with the class name;
  • It has accessibility, with public, protected or private.

So, if you have access to the static member function and decorate it correctly, then you can point to the function like any normal function outside a class:

typedef int Fn(int); // Fn is a type-of function that accepts an int and returns an int

// Note that MyFn() is of type 'Fn'
int MyFn(int i) { return 2*i; }

class Class {
public:
    // Note that Static() is of type 'Fn'
    static int Static(int i) { return 3*i; }
}; // Class

int main() {
    Fn *fn;    // fn is a pointer to a type-of Fn

    fn = &MyFn;          // Point to one function
    fn(3);               // Call it
    fn = &Class::Static; // Point to the other function
    fn(4);               // Call it
 } // main()