kadina
kadina

Reputation: 5372

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

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?

Upvotes: 0

Views: 722

Answers (3)

xvnm
xvnm

Reputation: 481

I assume that you meant

// inside class definition block
static const int a = 0;
static int b = 0;       // error 

C++ Standard 9.4.2/4,

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.

It is specified in standard.

Edit:

as 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

If a non-volatile non-inline const static data member is of integral or enumeration type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression (8.20). The member shall still be defined in a namespace scope if it is odr-used (6.2) in the program and the namespace scope definition shall not contain an initializer. An inline static data member may be defined in the class definition and may specify a brace-or-equal-initializer . If the member is declared with the constexpr specifier, it may be redeclared in namespace scope with no initializer (this usage is deprecated; see D.1). Declarations of other static data members shall not specify a brace-or-equal-initializer.

Upvotes: 3

Serge
Serge

Reputation: 12384

classes are usually declared in header files. Header files can be included multiple times in body files. If a static member, which needs memory, is defined within a class, than there will be a different copy of such a member in different body files. This will kill the idea of static members.

Constants on the other hand do not use memory and are compile-only constructs. therefore declaring them in the classes does not do any harm.

Upvotes: -1

Ed Heal
Ed Heal

Reputation: 60047

One needs a bit of space in memory. Const do not - they can be hard coded.

Upvotes: 1

Related Questions