Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the proper "C++ way" to do global variables?

I have a main application class, which contains a logger, plus some general app configurations, etc.

Now I will display a lot of GUI windows and so on (that will use the logger and configs), and I don't want to pass the logger and configurations to every single constructor.

I have seen some variants, like declaring the main class extern everywhere, but that doesn't feel very object oriented. What is the "standard" C++ way to make elements in the main class accessible to all (or most) other classes?

like image 385
Rolle Avatar asked Apr 21 '09 13:04

Rolle


People also ask

How do you define a global variable in C?

The variables that are declared outside the given function are known as global variables. These do not stay limited to a specific function- which means that one can use any given function to not only access but also modify the global variables.

Is it good practice to use global variables in C?

Master C and Embedded C Programming- Learn as you goUsing global variables causes very tight coupling of code. Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value.

Can C have global variables?

The C compiler recognizes a variable as global, as opposed to local, because its declaration is located outside the scope of any of the functions making up the program. Of course, a global variable can only be used in an executable statement after it has been declared.

Where do global variables go in C?

Global variables are defined outside a function, usually on top of the program.


2 Answers

Use the singleton design pattern.

Basically you return a static instance of an object and use that for all of your work.

Please see this link about how to use a singleton and also this stackoverflow link about when you should not use it

Warning: The singleton pattern involves promoting global state. Global state is bad for many reasons.
For example: unit testing.

like image 99
Brian R. Bondy Avatar answered Oct 08 '22 10:10

Brian R. Bondy


It is not so bad idea to pass the logger and config to all the constructors if your logger and config is abstract enough.

Singleton can be a problem in the future. But it seams like a right choice in the project begin. Your choice. If your project is small enough - go with singleton. If not - dependency injection.

like image 31
Mykola Golubyev Avatar answered Oct 08 '22 11:10

Mykola Golubyev