Search code examples
c++staticinitializationconstantsexecution-time

Better way to initialize a "static const"-type variable member of a class in the main


I have a class that needs a static const variable member. The value for that class will be known at runtime by a user input. I have read a lot of post but so far none of the solution works. I am aware that this post:

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

contains a work around, but it uses a global variable that I'd like to avoid. And also it doesn't really solve the problem.

Consider this:

#include

class A {
  friend void foo(int);
    static int dummy;
public:
    static const int &T;
};

const int &A::T = A::dummy;
int A::dummy = 0;

void foo(int val) { A::dummy = val; }

int main() {
    foo(10);
    std::cout << A::T << std::endl;
    foo(12);
    std::cout << A::T << std::endl;
}

The program will compile and write 10 and 12 in the console. Wich defeats the purpose of the const qualifier. What is const here is the reference not the value. So I have come to the conclusion that it is not possible to have a static const class variable at execution time!

I know another way involving creating a setting-type class but it is not very neat.

So if someone knows a simple solution, please let us know!


Solution

  • There is also something wrong with the solutions that I provided in the link of my original question and in the other solution I got. Consider this: #include

    class A {
      friend void foo(int);
        static int dummy;
    public:
        static const int &T;
    };
    
    const int &A::T = A::dummy;
    int A::dummy = 0;
    
    void foo(int val) { A::dummy = val; }
    
    int main() {
        foo(10);
        std::cout << A::T << std::endl;
        foo(12);
        std::cout << A::T << std::endl;
    }
    

    The program will compile and write 10 and 12 in the console. Wich defeats the purpose of the const qualifier. What is const here is the reference not the value. So I have come to the conclusion that it is not possible the have a static const class variable at execution time!