I have a class with some static members, and I want to run some code to initialize them (suppose this code cannot be converted into a simple expression). In Java, I would just do
class MyClass {
static int field1;
static int field2;
static {
/* do some computation which sets field1 and field2 */
}
}
Unless I'm mistaken, C++ does not allow for such static code blocks, right? What should I be doing instead?
I would like solution for both of the following options:
- Initialization happens when process loads (or when the DLL with this class is loaded).
- Initialization happens when the class is first instantiated.
For the second option, I was thinking of:
class StaticInitialized {
static bool staticsInitialized = false;
virtual void initializeStatics();
StaticInitialized() {
if (!staticsInitialized) {
initializeStatics();
staticsInitialized = true;
}
}
};
class MyClass : private StaticInitialized {
static int field1;
static int field2;
void initializeStatics() {
/* computation which sets field1, field2 */
}
};
but that's not possible, since C++ (at the moment?) does not allow initialization of non-const static members. But, at least that reduces the problem of a static block to that of static initialization by expression...
static block
be separate for each class? Or does a single one suffice? Why not create an initializing function and call it inmain
? – Karmenmain()
. "Why not... call it inmain()
"? So that main doesn't have to know about it of course. – Wite