Reputation: 207
When declaring a static constant array in my class like that
static const int myArray[] = {1, 2, 3, 999};
I get an error like "In-class initializer for static data member of type const int[] requires constexpr specifier". When I make it this way and declare it as
static constexpr int myArray[] = {1, 2, 3, 999};
it works. Why is it not possible to declare static constant arrays? What am I missing?
Upvotes: 0
Views: 610
Reputation: 568
It seems that there is a bit of confusion about declaration and definition / initialization in the question.
Before C++11, the definition (which often includes the initialization) of a static member should be done out-of-class, with the exception of static constants of integral or enumeration types. From Stroustrup's C++ FAQ:
to use in-class initialization syntax, the constant must be a static const of integral or enumeration type initialized by a constant expression
Even in this case, if the definition is required (e.g when taking the address of the static member), it should be defined out-of-class.
C++11 introduces the constexpr
specifier to signal compile time initialization, and allows static members to be initialized in-class if declared constexpr
(check Constant static members section in the reference of static
). It also allows in-class initialization of non-static members but with a wider meaning.
Upvotes: 2