Reputation: 6393
I want to create an environment class that is accessible from all of my classes in my program but I dont want to initialize the environment object everytime I want to access its members from my other classes. What is the best way to go around doing this in C++?
I want to do this because I have the environment object store all my config values that other classes may use. Those values are read from multiple places, including different files. I dont want to parse the files every time I create a new environment object in my classes.
Upvotes: 2
Views: 1109
Reputation: 95589
As has been pointed out, what you are looking for is the Singleton pattern. However, the Singleton pattern is frequently the result of poor design. Whenever you find yourself using the Singleton pattern, or, for that matter, any pattern that requires what are, in effect, global variables, you should consider whether there might be a better approach to the problem. With respect to your particular problem, I recommend you take a look at the QSettings class, which is a part of the Qt Framework, a free and high quality open source library.
The QSetttings class will allow you to load/save configuration settings using the preferred native mechanism (the registry on Windows, a property list file on Mac OS X, and a gconf XML file on Linux). Also, you might want to see my post Environment Variables are Evil, in case you were considering using environment variables for the configuration (the name "environment" for the configuration sounds awfully ominous).
Upvotes: 0
Reputation: 20881
A Singleton object isn't always the solution. While sometimes it seems like an easy solution, it does have some disadvantages (see this question for example).
How many of your classes actually need access to this Environment object? If you literally meant that every class you have do then it sounds like your design is flawed.
Quite often a better alternative to a singleton is just to pass the object around to those who actually need it.
Upvotes: 5
Reputation: 14446
You can create a service which is a static singleton. This service contains all your object collection(s) and provide functions to access these objects.
Upvotes: -1
Reputation: 2157
Sounds like you want a singleton pattern. This will let you create and use one object/instance of a class, but no more, even if you access it many times. See:
http://www.infernodevelopment.com/singleton-c
Upvotes: -1
Reputation: 7503
What you need to do is to wrap your environment class in a Singleton Pattern. See this SO question for more info: C++ Singleton design Pattern
Upvotes: 0