Read constants from command line as global variables

894 views Asked by At

In my program I have defined a header constants.h where I define constants that will be used in my program, which contains multiple classes. No I would like to read the constants from the command line and initialize these constants such that they can be used in the same way as before.

constants.h:

const int FOO = 10;

classA.cpp:

#include "constants.h" 
// uses FOO 

classB.cpp:

#include "constants.h" 
// uses FOO

My idea was to read the value for FOO and pass it over to the two classes as member variables when I creat the object in the main class. But I dont think this is a good idea, because of redundancy.

2

There are 2 answers

0
Maciej Baranowski On BEST ANSWER

Your program has multiple classes, so I suppose you are programming using Object-oriented paradigm - global variables are discouraged in such projects. Of course introducing information redundancy is also bad.

What you can do is make a new class that would store all constants and would be responsible for reading them in command line. Then you can store references to objects of this class in classA and classB and wherever else you need those constants

0
Rushikesh Deshpande On

As mentioned in previous answer, you should not declare global variables in object oriented programming.

But I think what you are trying to do is define variables at run time and make them constant for no future change in other classes. For solving the problem you can define a class with global variables and create an instance of this class globally.

Again most efficient way is create a configuration file instead of command line arguments for variable values.