C++ – How to make variable of the class initialize only once

c

I have a class called class object which have variable called density (_OMEGA is related to density : density = _OMEGA*x). I also have configuration file(a txt file) where I say _OMEGA = 1.4. Then I read that _OMEGA and other configuration variable from the txt file into a container in class config which I will be using in my project during runtime.

Now I make lots of this class object, since I make many of them I don't want to pass _OMEGA to each of these object during creation since I don't want to store this _OMEGA in each of these class object. (I use _OMEGA just to vary the density variable in class object)

I know static variable are idle for these case but I am not sure how to go ahead and use it.

  • I know MACRO are idle for this but I don't want to use them in this particular case.

What I have done so far is :

In main.cpp after reading the config file I do

object::_OMEGA = config.get_val("OMEGA");

I get undefined reference to object::_OMEGA

I think why I get this error since I did not do the
object::_OMEGA = config.get_val("OMEGA"); in the cpp file. But if I do this in cpp file then I have to pass the config reference to all object class, which seems counter productive.

To avoid this error I did :

double object::_OMEGA = 0; 

and in .h file of object I declared a variable static double _OMEGA

I now compiles but now sure if this is the right way to do thing.

Best Answer

since I make many of them I don't want to pass _OMEGA to each of these object during creation

You don't really have a choice. The other alternatives suck much more, it's just over a longer period of time.