Why use static const (int / string / ..) when you can keep it private?
In C ++, a marked member static
is shared by all instances of the given class. Whether it is private or not does not affect the fact that one variable is used by multiple instances. When present, const will warn you if any code tries to change this.
If it was strict private
, then each instance of the class would get its own version (despite the optimizer).
^ Here's 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 that each object will have its own, but why is that bad?
source to share
You hinted at the answer yourself, despite the "optimizer". Trust the compiler and target for clarity.
Indeed, you are correct here, also note the stronger condition that the behavior when trying to change a variable declared as const
undefined. So you cannot hack this by using const_cast
& c pointers as well.
Do what feels most natural. Yes, it's subjective, but for what it's important, I prefer to use variables private
instead of variables private
static
because (i) it's more symmetric, (ii) easier to refactor, protected
or public
(iii) private
members work better with base member initialization.
source to share
I know that each object will have its own, but why is that bad?
Because if each object doesn't need its own, you've wasted resources and introduced a class implementation that doesn't accurately represent its semantics.
It static
can also be referred to in some contexts where members cannot (for example, navigate to the C API).
source to share
The whole point of defining most constants is that there is only one. For example, if I define const double pi = 3.14159...;
, I certainly don't want a second instance of that value to exist. Otherwise, I would be interested to know if it really a.pi
matches b.pi
. When I know that it is announced as static const
, I am sure that a.pi == b.pi
. The same applies to typical values static const
that act like enum
bitfield constants.
Also advise the recommendation BoundaryImposition : a non-static one const
consumes as much memory as a non-constant data item. If you cannot declare your constants static
, you are bloating your objects significantly.
Finally, there are good use cases for non-static constant members: they depend on how the object was initialized, but are guaranteed not to change throughout the life of the object. So the following
const int before = a.nonStaticConstant;
a.modify();
assert(a.nonStaticConstant == before);
you can reasonably expect it to succeed (we're talking C ++, so anything is possible, including changing constants!), although a.nonStaticConstant == b.nonStaticConstant
it most likely won't work.
source to share