65.9K
CodeProject is changing. Read more.
Home

Static Initialization Function in Classes

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.71/5 (27 votes)

Apr 8, 2007

CPOL
viewsIcon

73924

downloadIcon

160

Automaticlly invoke static initialization functions of classes.

Content

Sometimes when we write a C++ class, we want a static function to be used to initialize the class. For example, a static function is used to initialize a static vector or map. We can do the same thing easily in Java, by Java's static block. How we can do with C++?

At first, let's see how to initialize a normal static member in C++.

class Test1 {
public:
    static string emptyString;
};

string Test1::emptyString = "";
// also can be
// string Test1::emptyString;
// string Test1::emptyString("");

As you saw, we declare a static member variable in the class definition, then define and initialize it in the implementation file (.cpp).

Now we meet the first problem, how to initialize a static collection member? The answer is we must write a static function to do that.

And now we meet the second problem, how to invoke the initialization function? Normally, we will invoke the initialization function in the main function. But I think it's not a good solution because users may forget to invoke the initialization function.

Here is my solution:

class Test2 {
public:
    static vector<string> stringList;
private:
    static bool __init;
    static bool init() {
        stringList.push_back("string1");
        stringList.push_back("string2");
        stringList.push_back("string3");

        return true;
    }
};

// Implement
vector<string> Test2::stringList;
bool Test2::__init = Test2::init();

An additional static member is used in my solution. When the additional static member is initialized, the initialization function is invoked automatically.