Let us say that I have the classes M, A, B, C. M is the main class of my application (that is the one that does most of the job) and has this structure
class M {
public:
// Something here.
private:
Conifg config;
A a;
std::vector<B> bs;
const C* c;
};
In a main I create an instance m of class M and I want to set my config object, say by reading it from a file. The configuration object is nothing special, it could be a protocol buffer or a simple struct.
Now, I want a, b and c to be able to access the config object, because there are some global settings that they need. These settings are global, they do not change, and are the same for each instance of A, B and C (and M). What I am currently doing, is having a static field in each class A, B and C and I am setting a copy of the configuration object for each instance of these classes. I do not want these classes to know of the existence of M. Is this the best solution? Should I perhaps think of a global config variable?
Just pass the Config object to the A, B and C constructors (specifically, pass a reference to the Config object which is stored in M.
That gives you:
But whatever you do, don't use a singleton, and try to avoid static/global data in general.
I would advice you to use an additional static class for configuration, instead of static fields in all the classes, where you include its header in the places you want.
Implement a static constructor where you initialize all the data you want in the static members. I think this would be a better solution.
I personally would rather somehow pass that config object to A B C than use global/static objects. What about passing it (it's reference) as an argument upon construction of a b c, or setting it later via set_config() call?
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