Can I initialize a static const member at run-time in C++?
I am sorry to disagree with the comments and answers saying that it is not possible for a static const
symbol to be initialized at program startup rather than at compile time.
Actually this IS possible, and I used it many times, BUT I initialize it from a configuration file. Something like:
// GetConfig is a function that fetches values from a configuration file
const int Param1 = GetConfig("Param1");
const int MyClass::Member1 = GetConfig("MyClass.Member1");
As you see, these static consts are not necessarily known at compile time. They can be set from the environment, such as a config file.
On the other hand, setting them from argv[], seems very difficult, if ever feasible, because when main() starts, static symbols are already initialized.
You cannot rely on data produced after your main
has started for initialization of static
variables, because static initialization in the translation unit of main
happens before main
gets control, and static initialization in other translation units may happen before or after static initialization of main
translation unit in unspecified order.
However, you can initialize a hidden non-const variable, and provide a const
reference to it, like this:
struct A {
public:
// Expose T as a const reference to int
static const int& T;
};
//in main.cpp
// Make a hidden variable for the actual value
static int actualT;
// Initialize A::T to reference the hidden variable
const int& A::T(actualT);
int main(int argc,char** argv) {
// Set the hidden variable
actualT = atoi(argv[1]);
// Now the publicly visible variable A::T has the correct value
cout << A::T << endl;
}
Demo.