Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I initialize a static const member at run-time in C++?

Tags:

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.

like image 472
user2939212 Avatar asked Nov 06 '15 17:11

user2939212


People also ask

Are static variables initialized at compile time?

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.

How do you initialize a const member?

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.

Can we use static const in C?

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.

How many times static member variable is initialized?

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.


1 Answers

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.

like image 120
Sergey Kalinichenko Avatar answered Sep 22 '22 04:09

Sergey Kalinichenko