views:

95

answers:

5

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.

A: 

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

Peter M
A singleton is not a good approach for this. He should extract the necessary information from the configuration, and pass that to the object's constructor. Using a singleton makes the other objects unnecessarily coupled with the configuration logic, and it also makes it hard to instantiate objects if there is no loaded configuration.
Michael Aaron Safyan
A: 

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

Lee B
A: 

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.

Patrice Bernassola
+4  A: 

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.

Idan K
passing the object file worked best. Thanks
TP
A: 

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).

Michael Aaron Safyan