Home

Pointing to Static Member Functions in C++

|
Updated:  
2016-03-26 08:30:13
|
From The Book:  
C++ Essentials For Dummies
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:

public:
    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 Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.

Jeff Cogswell has been an application developer and trainer for 18 years, working with clients from startups to Fortune 500 companies. He has developed courses on C++ and other technologies.