Raghav Navada
Raghav Navada

Reputation: 317

Initialization of a static member inside a global function

My code looks like this:

class myClass{
    public:
        static int a;
};

void myFunc()
{
    int myClass::a = 1;
}

I see the following compilation error error C2655: 'myClass::a' : definition or redeclaration illegal in current scope

I make the following change and everything goes fine. Any idea?

class myClass{
    public:
        static int a;
};

int myClass::a = 1;
void myFunc()
{
}

Upvotes: 1

Views: 126

Answers (3)

RicoWijaya
RicoWijaya

Reputation: 15

Static variable must be initialized before program start, so if you initialized it in a function, there is chance that it will not be initialized at all. So the compiler should pose this as an error. Static variable is allocated at compile time (before program run). Hope this help.

Upvotes: 1

Mohit Jain
Mohit Jain

Reputation: 30489

Logically think like this:

If you never call myFunc(), myClass::a is not defined. So it must be in global scope.

In your first code snippet, potentially you may use myClass::a even without defining it, so it not allowed and former syntax is not valid C++.

Upvotes: 2

R Sahu
R Sahu

Reputation: 206627

If you define the static member data in a function, it's linkage is internal to the function. The linkage required for them is global.

Upvotes: 0

Related Questions