Could any body offer me any reason about that?
If we do it like that, what's the outcome? Compile error?
Could any body offer me any reason about that?
If we do it like that, what's the outcome? Compile error?
It is just a limitation in the language it self. Hopefully, when C++0x becomes reality, this limitation would go away.
I think this page gives a somehow good reason:
One of the trickiest ramifications of using a static data member in a class is that it must be initialized, just once, outside the class definition, in the source file. This is due to the fact a header file is typically seen multiple times by the compiler. If the compiler encountered the initialization of a variable multiple times it would be very difficult to ensure that variables were properly initialized. Hence, exactly one initialization of a static is allowed in the entire program.
The problem is that static initialization isnt just initialization, it is also definition. Take for example:
class Foo
{
public:
static std::string bar_;
};
std::string Foo::bar_ = "Hello";
std::string GimmeFoo();
#include <string>
#include <sstream>
#include <iostream>
#include "hacks.h"
using std::string;
using std::ostringstream;
using std::cout;
int main()
{
string s = GimmeFoo();
return 0;
}
#include <string>
#include <sstream>
#include <iostream>
#include "hacks.h"
using std::string;
using std::ostringstream;
using std::cout;
string GimmeFoo()
{
Foo foo;
foo;
string s = foo.bar_;
return s;
}
In this case, you can't initialize Foo::bar_ in the header because it will be allocated in every file that #includes hacks.h. So there will be 2 instances of Foo.bar_ in memory - one in main.cpp, and one in foo.cpp.
The solution is to allocate & initialize in just one place:
...
std::string Foo::bar_ = "Hello";
...
The "one definition rule" means that the member must be defined in just one compilation unit (in practice, that means in one source file, and not in a header file). Otherwise, there would be multiple definitions causing a link error.
As a special exception, you are allowed to initialise static constant integer members in the class definition, and these are treated as compile-time constants. If you need to create a pointer or reference to such a member, then it will need to be defined in one source file (although it can still be initialised in the class definition).