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?
A static data member can be of any type except for void or void qualified with const or volatile. You cannot declare a static data member as mutable.
Static members are data members (variables) or methods that belong to a static or a non static class itself, rather than to objects of the class. Static members always remain the same, regardless of where and how they are used.
“static const” is basically a combination of static(a storage specifier) and const(a type qualifier). The static determines the lifetime and visibility/accessibility of the variable.
An example of using static const member variables in C++ is shown below with common types (integer, array, object). Only one copy of such variable is created for its class. The variable cannot be modified (it is a constant) and is shared with all instances of this class.
You need to have your XML file read when you try to initialize the variable. However, you can get hold of it using a static
object inside a function:
XMLData const& access_config_file() {
static XMLData data = readXMLData();
return data;
}
You can then reference access_config_file()
from wherever you need to access it and pull the values out. The static
variable gets initialized the first time the function is called.
Make your XML class object a static member in this class too. i.e.,
class Human
{
public:
static XMLReader x;
static const int HANDS;
static const int FINGERS;
};
Then in the implementation file, you provide the definitions of these static members, i.e.,
XMLReader Human::x();
const int Human::HANDS= x.ReadDataFromFile();
const int Human::FINGERS =x.ReadDataFromFile();
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