Home:ALL Converter>why initialization of static member variable is not allowed inside class but initialization of const static members is allowed?

why initialization of static member variable is not allowed inside class but initialization of const static members is allowed?

Ask Time:2018-04-26T09:36:17         Author:kadina

Json Formatter

When I tried to initialize the static member variables at the time of declaration inside the class, compiler is throwing error as expected because we need to explicitly allocate the space for static member variables outside the class. I thought this should be same for static const variables. But to my surprise, initialization of static const member variables inside the class is working fine. Can any one please let me know why normal static member variable initialization is not allowed in the same way?

Author:kadina,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/50033574/why-initialization-of-static-member-variable-is-not-allowed-inside-class-but-ini
xvnm :

I assume that you meant\n\n// inside class definition block\nstatic const int a = 0;\nstatic int b = 0; // error \n\n\nC++ Standard 9.4.2/4,\n\n\n If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a name- space scope if it is used in the program and the namespace scope definition shall not contain an initializer.\n\n\nIt is specified in standard.\n\nEdit:\n\nas M.M pointed out, above quotation is actually not what the Standard says, and the correct one is C++ Standard 12.2.3.2/3\n\n\n If a non-volatile non-inline const static data member is of integral or enumeration type, its declaration\n in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an\n assignment-expression is a constant expression (8.20). The member shall still be defined in a namespace scope\n if it is odr-used (6.2) in the program and the namespace scope definition shall not contain an initializer. An\n inline static data member may be defined in the class definition and may specify a brace-or-equal-initializer .\n If the member is declared with the constexpr specifier, it may be redeclared in namespace scope with no\n initializer (this usage is deprecated; see D.1). Declarations of other static data members shall not specify a\n brace-or-equal-initializer.\n",
2018-04-26T01:55:48
Ed Heal :

One needs a bit of space in memory. Const do not - they can be hard coded.",
2018-04-26T01:44:28
yy