I am trying to define a public static variable like this :
public :
static int j=0; //or any other value too
I am getting a compilation error on this very line : ISO C++ forbids in-class initialization of non-const static member `j'.
Why is it not allowed in C++ ?
Why are const members allowed to be initialized ?
Does this mean static variables in C++ are not initialized with 0 as in C?
Thanks !
You will have to initialize the static variable in a .cpp file and not in the class declaration.
When you declare a static variable in the class, it can used without instantiating a class.
The short answer:
It's equivalent to saying
extern int Test_j = 0;
.If it did compile, what would happen? Every source file including your class's header file would define a symbol called Test::j initialized to 0. The linker tends not to like that.
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.
[dirkgently said it better]
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:
Until and unless you define it, the variable doesn't become a l-value.
Even in this case, a definition is required if you are going to take the address of the variable.
Also, this is primarily an usage artifact so that you can write:
No they are:
Though things get a bit more trickier in C++0x. All literal types can now be initialized (as opposed to only integral types in the current standard) which would mean that all scalar types (floats included) and some class types can now be initialized using an initializer in the declaration.