I'm trying to decide what the best option would be for when an object has some traits that won't change, and are needed throughout its functions.
It seems to me like the real reason for a static member is to have a variable that can be changed, and thus affect all other objects of the same class. However, I've had people recommend class "invariants" to be static const members. I'm looking for some insight regarding the recommended approach to establishing class constants, and reasons why.
An instance const value can be computed in the ctor-initializer-list. A static const is set during startup initialization and remains unchanged for the rest of the program.
The primary difference between const and constexpr variables is that the initialization of a const variable can be deferred until run time. A constexpr variable must be initialized at compile time.
A static keyword is been used to declare a variable or a method as static. A const keyword is been used to assign a constant or a fixed value to a variable. In JavaScript, the static keyword is used with methods and classes too. In JavaScript, the const keyword is used with arrays and objects too.
constexpr variable is guaranteed to have a value available at compile time. whereas static const members or const variable could either mean a compile time value or a runtime value. Typing constexpr express your intent of a compile time value in a much more explicit way than const .
A const
member should be used when that member doesn't change on a per-instance basis. A static const
member should be used when that member doesn't change on a per-class basis. In other words, no matter how many instances you create, the static const
member remains fixed between all instances whereas the const
member is constant only for a specific instance.
I'm not sure if that's what you're looking for since that's merely an explanation of how they behave, but I hope it helps somewhat.
"Won't change" is not precise enough. The main question here is whether different objects of the class need to have different values of these const members (even if they don't change during the object's lifetime) or all objects should use (share) the same value.
If the value is the same for all objects of the class, then, of course, it should be a static const
member of the class.
If different objects might require different values, then it should be just a non-static const
member.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With