Is it possible to initialize a static const member of my class during run-time? This variable is a constant throughout my program but I want to send it as a command-line argument.
//A.h class A { public: static const int T; }; //in main method int main(int argc,char** argv) { //how can I do something like A::T = atoi(argv[1]); }
If this cannot be done, what is the type of variable I should use? I need to initialize it at run-time as well as preserve the constant property.
Initialization of static variables happens in two consecutive stages: static and dynamic initialization. Static initialization happens first and usually at compile time. If possible, initial values for static variables are evaluated during compilation and burned into the data section of the executable.
To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.
const means that you're not changing the value after it has been initialised. static inside a function means the variable will exist before and after the function has executed. static outside of a function means that the scope of the symbol marked static is limited to that . c file and cannot be seen outside of it.
A static variable in a block is initialized only one time, prior to program execution, whereas an auto variable that has an initializer is initialized every time it comes into existence.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With