Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need static here?

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?

like image 526
markzzz Avatar asked Dec 02 '22 13:12

markzzz


2 Answers

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.

like image 101
Lightness Races in Orbit Avatar answered Feb 08 '23 18:02

Lightness Races in Orbit


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.

like image 29
Rama Avatar answered Feb 08 '23 16:02

Rama