3

How come the following code snippet is compiled with no error:

void func(){
    const int s_max{ 10 };
    int m_array[s_max]{0}; 
}

int main() {
    const int s_max{ 10 };
    int m_array[s_max]{0}; 
    return 0;
}

but when I try to define the same array within a class scope, I get the following error:

class MyClass
{
    const int s_max{ 10 }; 
    int m_array[s_max]{0}; // error: invalid use of non-static data member 's_max'
};

Why does s_max need to be static within the class?

I could not find a convincing answer to my question in other similar posts.

3
  • The length of an array must be a constant expression and const is necessary but not sufficient for a constant expression. Commented Aug 23, 2019 at 2:13
  • I have some bad news: even though the first snippet "compiled with no error", it is not valid C++. Your compiler is just doing you a favor, and allowing something that's not standard C++. Commented Aug 23, 2019 at 2:14
  • 1
    @SamVarshavchik I think the 1st case should be fine; s_max is a constant expression. has integral or enumeration type and refers to a complete non-volatile const object, which is initialized with a constant expression Commented Aug 23, 2019 at 2:20

1 Answer 1

4

As a non-static data member, it might be initialized with different values via different initialization ways (constructors (member initializer lists), default member initializer, aggregate initialization, etc). Then its value won't be determined until the initialization. But the size of raw array must be fixed and known at compile-time. e.g.

class MyClass
{
    const int s_max{ 10 }; 
    int m_array[s_max]{0}; // error: invalid use of non-static data member 's_max'
    MyClass(...some arguments...) : s_max {20} {}
    MyClass(...some other arguments...) : s_max {30} {}
};
Sign up to request clarification or add additional context in comments.

2 Comments

I see, so when we make it static (and we have to also assign it a value), it will be known at compile time and won't depend on different initializations, right?
@Monaj Yes, static members can't be initialized in different uncertain ways.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.