C++ All-in-One For Dummies
Book image
Explore Book Buy On Amazon

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.

About This Article

This article is from the book:

About the book author:

John Mueller has produced 114 books and more than 600 articles on topics ranging from functional programming techniques to working with Amazon Web Services (AWS). Luca Massaron, a Google Developer Expert (GDE),??interprets big data and transforms it into smart data through simple and effective data mining and machine learning techniques.

This article can be found in the category: