static constructors in C++? I need to initialize private static objects
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_;
public:
StaticStuff()
{
for (char c = 'a'; c <= 'z'; c++)
letters_.push_back(c);
}
// provide some way to get at letters_
};
class Elsewhere
{
static StaticStuff staticStuff; // constructor runs once, single instance
};
In the .h file:
class MyClass {
private:
static int myValue;
};
In the .cpp file:
#include "myclass.h"
int MyClass::myValue = 0;
C++11 update
Since C++11, you can simply use lambda expressions to initialize static class members. You don't need to use any helper classes or workarounds anymore.
Header file:
class MyClass {
static const vector<char> letters;
};
Source file:
// Initialize MyClass::letters with all letters from 'a' to 'z'.
const vector<char> MyClass::letters = [] {
vector<char> letters;
for (char c = 'a'; c <= 'z'; c++)
letters.push_back(c);
return letters;
}();
Note about static initialization order:
This approach also works if multiple static class members must be initialized in some specific order. Since static members are always initialized in the exact same order as defined within the source file, you just simply have to make sure that you write your initializations within the source file in the correct order.
Well you can have
class MyClass
{
public:
static vector<char> a;
static class _init
{
public:
_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.