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.
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} {}
};
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