-2

I have class Config:

class Config
{
    public:
        Config();
        ~Config();
        void Read();
        CData var; //CData - some config structure
};

What's the right way to access the values from other classes? There are a few options:

  1. make it global
  2. transfer reference to other classes
  3. your variant

In my system, config.var.some is needed in 90% of classes.

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
askovpen
  • 2,438
  • 22
  • 37
  • 1
    possible duplicate of [Which design patterns can be applied to the configuration settings problem?](http://stackoverflow.com/questions/1314730/which-design-patterns-can-be-applied-to-the-configuration-settings-problem) – johnsyweb Apr 24 '12 at 23:16

3 Answers3

3

3) You can use statics, which is basically like making it global.

class Config
{
    public:
        static CData var; //CData - some config structure
        static CData Read();
};

//these in a cpp file
CData Config::var = Config::Read();

int main() {
    std::cout << Config.var.something;
}

but in this case, it's probably best just to make var itself global.

Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
0

The third way: add accessor functions to Config class.

class Config
{
    public:
        Config();
        ~Config();
        void Read();
        int getNumberOfFooBars() const { return var.foo_bars; }
private:
        CData var; //CData - some config structure
};
jpalecek
  • 47,058
  • 7
  • 102
  • 144
  • I think he wants a single `Config` singleton sort of thing. – Mooing Duck Apr 24 '12 at 23:15
  • Ah, so. Then I vote for making it global (or an equivalent approach like making it a member of another global singleton instance like `QApplication`). – jpalecek Apr 24 '12 at 23:22
  • don't understand. in e.g main() i make Config.Read() - parse config files. how next in some classes i get result with you suggestion? – askovpen Apr 24 '12 at 23:23
0

I would generally pass an object like this as a reference rather than being lazy and making it global. If you pass the object, then it is very obvious which classes are going to use the object by looking at the constructors / member initializer list. Conversely, Making it global (as a singleton or whatever) makes it hard for you, or others to see which classes require the object at a glance.

Add accessor functions to the config class that allow other objects to access its members through a defined interface. This will allow you to change the internals of the class without breaking the code that interfaces with the config class.

learnvst
  • 15,455
  • 16
  • 74
  • 121