Search code examples
c++classstaticconstants

Why can't I declare class-scope constants without using 'static'?


I'm an OOP newbie and just learning classes. Why can't I create constants and use them in classes without the static specifier? Like this:

class MyClass{
private:
   const int MyConst = 10;
   int MyArr[MyConst];
};

The compiler complains that:

invalid use of non-static data member ‘MyClass::MyConst’
'MyArr' was not declared in this scope

I checked out some tutorials, like C++ Primer Plus, which tells me to create an enumeration. Why do enumerations work? Don't they create constants like using the const qualifier?


Solution

  • An array needs a constant expression for its size, such as a compile-time constant.

    Without static, your MyConst value would be an instance member of MyClass. You would have to allocate an object instance of the class at runtime in order to access MyConst's value, as its location in memory would depend on where the object is allocated. So, you can't use MyConst as an instance member in a constant expression, even with the const. The const just means MyConst's value can't be changed at runtime after it has been initialized during the object's creation.

    Making MyConst be static frees it from any particular instance of MyClass at runtime. It can now be referred to at compile-time. Added with const, that then allows the compiler to use MyConst's value in constant expressions.

    An enum is a type. Its members have constant values at compile-time. So, you can a non-instance enum value wherever a constant expression is needed, without having to use static.