I have a variety of constants that I need to reference throughout my program. Rather than using global variables, I’ve been using static const class members:
class Human
{
public:
static const int HANDS = 2;
static const int FINGERS = 10;
};
The problem is that I need to read the value in from an XML data file. I know that I can initialize a static member with a function:
const int Human::HANDS = ReadDataFromFile();
Since the order of initialization can only be predicted in the same compilation unit, I have to define all of them in the same CPP file. That’s not really a problem but it gets a bit cluttered.
The real problem is that everything in my ReadDataFromFile() function needs to be ready for use before my code even has a chance to run. For instance, I have an XML class that normally handles reading XML data from files. I can’t use it in this case, though, because the static members are initialized before my XML class object is even constructed.
Aside from random global variables everywhere, is there a better solution to organize constants?
You need to have your XML file read when you try to initialize the variable. However, you can get hold of it using a
staticobject inside a function:You can then reference
access_config_file()from wherever you need to access it and pull the values out. Thestaticvariable gets initialized the first time the function is called.