skydoor
skydoor

Reputation: 25898

Why can't initialize the static member in a class in the body or in the header file?

Could any body offer me any reason about that?

If we do it like that, what's the outcome? Compile error?

Upvotes: 0

Views: 989

Answers (3)

user20562802
user20562802

Reputation:

Why can't we initializer a static data member in the class body or in the header file

We can, starting from C++17 we can use inline keyword to define a static data member right inside the class without any need to initialize it later outside the class.

For example, we can have the following in c++17

#include <string>

struct C
{
   static inline std::string var = "initializer inside class";
};
//no need for initialization here outside the class

Upvotes: 0

John Dibling
John Dibling

Reputation: 101506

The problem is that static initialization isn't just initialization, it is also definition. Take for example:

hacks.h :

class Foo
{
public:
    static std::string bar_;
};

std::string Foo::bar_ = "Hello";

std::string GimmeFoo();

main.cpp :

#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;
}

foo.cpp :

#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:

foo.cpp :

...
std::string Foo::bar_ = "Hello";
...

Upvotes: 5

Khaled Alshaya
Khaled Alshaya

Reputation: 96899

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.

Upvotes: 5

Related Questions