user974967
user974967

Reputation: 2946

static const class members

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?

Upvotes: 6

Views: 2443

Answers (2)

Vivek Tyagi
Vivek Tyagi

Reputation: 31

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();

Upvotes: 3

Dietmar Kühl
Dietmar Kühl

Reputation: 154035

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.

Upvotes: 5

Related Questions