static constructors in C++? I need to initialize private static objects


I want to have a class with a private static data member (a vector that contains all the characters a-z). In java or C#, I can just make a "static constructor" that will run before I make any instances of the class, and sets up the static data members of the class. It only gets run once (as the variables are read only and only need to be set once) and since it's a function of the class it can access its private members. I could add code in the constructor that checks to see if the vector is initialized, and initialize it if it's not, but that introduces many necessary checks and doesn't seem like the optimal solution to the problem.

The thought occurs to me that since the variables will be read only, they can just be public static const, so I can set them once outside the class, but once again, it seems sort of like an ugly hack.

Is it possible to have private static data members in a class if I don't want to initialize them in the instance constructor?

6/14/2016 4:10:38 AM

Accepted Answer

To get the equivalent of a static constructor, you need to write a separate ordinary class to hold the static data and then make a static instance of that ordinary class.

class StaticStuff
     std::vector<char> letters_;

         for (char c = 'a'; c <= 'z'; c++)

     // provide some way to get at letters_

class Elsewhere
    static StaticStuff staticStuff; // constructor runs once, single instance

7/29/2009 10:59:28 AM

Well you can have

class MyClass
        static vector<char> a;

        static class _init
            _init() { for(char i='a'; i<='z'; i++) a.push_back(i); }
        } _initializer;

Don't forget (in the .cpp) this:

vector<char> MyClass::a;
MyClass::_init MyClass::_initializer;

The program will still link without the second line, but the initializer will not be executed.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow