Defining static members in C++

(1.) Why is it not allowed in C++ ?

From Bjarne Stroustrup’s C++ Style and Technique FAQ:

A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.

(2.) Why are const members allowed to
be initialized ?

[dirkgently said it better]

(3.) Does this mean static variables
in C++ are not initialized with 0 as
in C?

As far as I know, as long as you declare the static member var in a .cpp it will be zero-initialized if you don’t specify otherwise:

// in some .cpp
int Test::j; // j = int();

Leave a Comment