I want to have a class with a private static data member:
class C {
// read-only, can also be static const
// should be filled with all characters from 'a' to 'z'
static std::vector<char> alphabet;
public:
C() { /* ... */ }
};
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 C()
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 member is read-only, so it can be static const
and I can define it outside the class, but that seems 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?
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
};