At class scope,
int MyClass::classVar = 0; // Why I have to init it here?
is a definition and
static int classVar;
is a declaration, ie. a promise the variable will be defined somewhere: you must define exactly once the variables you declare.
The rationale is that the class declaration will likely be included in multiple source files. Would a part of it be a definition, it would take place multiply: this is erroneous (exceptions are inline [member] functions).
Note that according to value initialization rules, you can get along with
int MyClass::classVar; // Zero-initialized !
as a definition.
Variables declared at namespace scope are definitions too (unless they are extern
qualified):
int var;
is a declaration, and a definition: if you put this into a header and include it in multiple translation units, you have an error ("multiply defined symbol", or something along those lines).
[Note that in C++ (and not in C), if the var
above is const
, it becomes automatically static
and there is no violation of the One Definition Rule should it be put into a multiply included header. This goes slightly off topic, but feel free to ask details]