Why I can write this:
class VoiceManager
{
public:
static const int mMaxNumOfVoices = 16;
Voice mVoices[mMaxNumOfVoices];
private:
};
but I can't use this:
class VoiceManager
{
public:
const int mMaxNumOfVoices = 16;
Voice mVoices[mMaxNumOfVoices];
private:
};
It says: "a nonstatic member reference must be relative to a specific object"
But in both case, mMaxNumOfVoices
is a const
and will be init before mVoices
init (compiler follow the declaration order, no?).
But it requires static
. Why?
Array bounds must be known at compile-time. Though your initialisation is written there in the code, it can be overridden at runtime by a constructor. Hence your non-static
member variable is not a compile-time constant.
The const
keyword means read-only, not constant, is like a not-be-changed promise for a specific part of the program. If you have a pointer-to-const then other parts of the program may change the value while you're not looking.
But a static const
is guaranteed that remains unchanged for the rest of the program. The storage for the object is allocated when the program begins and deallocated when the program ends. Only one instance of the object exists. All objects declared at namespace scope (including global namespace) have this storage duration.
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