3

In C++, a member marked static is shared by all instances of a given class. Whether it's private or not doesn't affect the fact that one variable is shared by multiple instances. Having const on there will warn you if any code would try to modify that.

If it was strictly private, then each instance of the class would get its own version (optimizer notwithstanding).

^This is what i read here. My question is, why is it better to have static const int instead of putting the desired variable in private? I know each object would get its own, but why is it bad?

Community
  • 1
  • 1
Yanketz
  • 79
  • 11

3 Answers3

5

You hinted at an answer yourself with "optimizer notwithstanding". Trust the compiler and aim for clarity.

Indeed you are correct here, also note the stronger condition that the behaviour on attempting to modify a variable that's declared as const is undefined. So you can't hack round this using const_casts and pointers &c.

Do whatever feels most natural. Yes it's subjective, but for what it's worth I tend to use private automatic variables rather than private static variables as (i) it's more symmetrical, (ii) it's simpler to refactor to protected or public and (iii) private members work better with base member initialisations.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

I know each object would get its own, but why is it bad?

Because if each object doesn't need its own, you have wasted resources and made a class implementation that does not accurately represent its semantics.

Also, statics may be referred to in some contexts where members cannot (passing to C APIs, for example).

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

The whole point of defining most constants is that there is only one. For instance, if I define const double pi = 3.14159...;, I most certainly do not want a second instance of that value to exist. Otherwise I would have to wonder whether a.pi is really the same as b.pi. When I know that it's declared as static const, I'm certain that a.pi == b.pi. The same goes for typical static const values that act like enums or bitfield constants.

Also heed BoundaryImposition's advice: A non-static const consumes as much memory as a non-const data member. If you fail to declare your constants static, you are bloating your objects significantly.

Finally, there are good use-cases for non-static const members: These depend on how the object was initialized, but are guaranteed to not change during the lifetime of the object. Thus, the following

const int before = a.nonStaticConstant;
a.modify();
assert(a.nonStaticConstant == before);

can reasonably be expected to succeed (we are talking C++, so anything is possible, including constants changing!), even though a.nonStaticConstant == b.nonStaticConstant is likely to fail.

Community
  • 1
  • 1
cmaster - reinstate monica
  • 38,891
  • 9
  • 62
  • 106