Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modify a static member variable in C++

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?

like image 521
yang Avatar asked Nov 18 '12 18:11

yang


2 Answers

Put this in your Util.cpp (or whatever the filename is) file:

double Util::MAX_DIST = 0;

Static variables need to be initialized.

Long answer, quoting the standard 9.4.2 $2:

The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition. In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the :: operator. The initializer expression in the definition of a static data member is in the scope of its class (3.3.7).

like image 165
Vincenzo Pii Avatar answered Sep 26 '22 12:09

Vincenzo Pii


In the first case, you are trying to initialize a static variable from within a non-static context, i.e. from within a constructor. You are correct that this is wrong.

In the second case, you do not want your variable to be const. Instead, you need to declare it outside of the class, using a statement like:

double Util::MAX_DIST = 400;
like image 35
Xymostech Avatar answered Sep 25 '22 12:09

Xymostech