I am trying to define a class Util with a static member variable MAX_DIST, in the following sense,
class Util{
public:
static double MAX_DIST;
Util():MAX_DIST(400.0){}
};
and be able to update it in some other class, e.g.
Util::MAX_DIST = 387.98;
This gives me an error:
‘double Util::MAX_DIST’ is a static data member; it can only be initialized at its definition
However, if I initialize MAX_DIST at its definition, such as
class Util{
public:
static const double MAX_DIST = 400;
Util();
};
(I have to add the ‘const’ as instructed by the compiler, otherwise I will get an “ISO C++ forbids in-class initialization of non-const static member” error)
Now I can not modify MAX_DIST in other places since it is now ready only:
error: assignment of read-only variable ‘Util::MAX_DIST’
After fruitless search on the internet, I can not find a solution to this paradox. Can someone help me out?
You’re confusing definition and declaration. You are trying to initialise in the latter – C++ forbids that. The other answers have shown you how the definition looks like: it has to be outside the class declaration, and in its own compilation unit (otherwise you’ll violate the One Definition Rule when you try including the header in several source files).
A word on why the original code didn’t work: you tried putting the initialisation into the initialiser list of the constructor. However, this constructor is called for every instance. Even if that code compiled, it would always reset your static variable – not what you want.