#include "stdafx.h"
#include <iostream>
class X {
public:
static int n;
};
int X::n; // out-of-class initialization
int _tmain(int argc, _TCHAR* argv[])
{
X x;
std::cout << x.n << std::endl;
return 0;
}
Without out-of-class initialization there will be unresolved externals linker error.
But what is the reason for that? The class declaration specifies it as a static member and I am not even assigning a value n:
int X::n;
When I print it, n has the value 0. So it is default initialized.
If so, then what is the need and why the compiler cannot do the default initialization from the class declaration only? Compiler clearly can see that class X has a static int member n, why it needs to be defined out of the class?
Thank you.