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?
It certainly doesn't need to be as complicated as the currently accepted answer (by Daniel Earwicker). The class is superfluous. There's no need for a language war in this case.
.hpp file:
.cpp file:
A static constructor can be emulated by using a friend class or nested class as below.
Output:
Test::StaticTest()
is called exactly once during global static initialization.Caller only has to add one line to the function that is to be their static constructor.
static_constructor<&Test::StaticTest>::c;
forces initialization ofc
during global static initialization.Is this a solution?
Here's another method, where the vector is private to the file that contains the implementation by using an anonymous namespace. It's useful for things like lookup tables that are private to the implementation:
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.