Pointing to Static Member Functions in C++ - dummies

Pointing to Static Member Functions in C++

By John Paul Mueller, Jeff Cogswell

A static member function is, in many senses, just a plain old function. The difference is that you have to use a class name to call a static function. But remember that a static member function does not go with any particular instance of a class; therefore you don’t need to specify an instance when you call the static function.

Here’s an example class with a static function:

    static string MyClassName() {
        return "Gobstopper!";
    int WhichGobstopper;
    int Chew(string name) {
        cout << WhichGobstopper << endl;
        cout << name << endl;
        return WhichGobstopper;

And here’s some code that takes the address of the static function and calls it by using the address:

typedef string (*StaticMember)();
StaticMember staticfunc = &Gobstopper::MyClassName;
cout << staticfunc() << endl;

Note that in the final line, you didn’t have to refer to a specific instance to call staticfunc() — and you didn’t need to refer to the class, either. You just called it. Because the truth is that deep down inside, the static function is just a plain old function.