Static const definition outside class definition

Should we define a static const element outside the class definition, even if it is initialized inside the class?

 #include<iostream> using namespace std; class abc { static const int period=5; int arr[period]; public: void display() { cout<<period<<endl; } }; const int abc::period; int main() { abc a; a.display(); return 0; } 

After commenting // const int abc::period; both versions of the code work fine on gcc 4.3.4. Therefore, I want to ask why both versions work, and which one conforms to the standard?

+6
source share
1 answer

You define the static member of period by writing const int abc::period; . You can provide an initializer in the class for a member of the static const class, but this is not a definition, but just a declaration.

9.4.2 / 4 - If a static data member is of type const integer or const, its declaration in the class definition may indicate a constant initializer, which should be an integral constant expression (5.19). In this case, the term can appear in integral constant expressions. A member still needs to be defined in the namespace area, if used in the program, and the namespace area definition should not contain an initializer.

Your code compiles even without a definition, because you do not take the address of a static member. Bjarne Stroustrup mentions in C ++ - the FAQ here is that you can take the address of a static member if (and only if) it has a class definition outside

+8
source

Source: https://habr.com/ru/post/888876/


All Articles