vrbilgi
vrbilgi

Reputation: 5793

Initialization of static class variable inside the main

I have a static variable in the class. I am Initializing that in the global scope, its works fine.

But When I try to Initialize in the main linker throws an error. Why it so.

class Myclass{

    static int iCount;
} ;

int main(){

  int Myclass::iCount=1;

}

And In global scope why I have to specify the variable type like

int Myclass::iCount=1;

As In my class I am definig iCount as integer type why not.

   Myclass::iCount =1 ; in //Global scope

Upvotes: 7

Views: 4530

Answers (5)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361342

The section $9.4.2/7 from the C++ Standard says,

Static data members are initialized and destroyed exactly like non-local objects (3.6.2, 3.6.3).

Note the phrases "initialized" and "exactly like non-local objects". Hope that explains why you cannot do that.

In fact, static members are more like global objects accessed through Myclass::iCount. So, you've to initialize them at global scope (the same scope at which class is defined), like this:

class Myclass{

    static int iCount;
} ;
int Myclass::iCount=1;

int main(){
  /*** use Myclass::iCount here ****/
}

Similar topic:

How do static member variables affect object size?

Upvotes: 5

Stephane Rolland
Stephane Rolland

Reputation: 39906

this is the correct C++. Outside of a function, in a cpp file. the initialisation is done at the beginning/launching of the executable. ( even before calling main() );

//main.h

class Myclass{

    static int iCount;
}; // and don't forget this ";" after a class declaration


//main.cpp

int Myclass::iCount=1;

int main(){



}

Upvotes: 3

Bojan Komazec
Bojan Komazec

Reputation: 9526

From C++ standard (§8.5/10):

An initializer for a static member is in the scope of the member’s class.

class Myclass has global scope and you tried to initialize its static member in the narrower scope - of the function main.

Upvotes: 2

Clifford
Clifford

Reputation: 93476

The static initialisation occurs before main is called by the run-time initialisation.

Placing it within a function is not allowed because that is where locally scoped objects are declared. It would be confusing and ambiguous to allow that.

Upvotes: 1

peoro
peoro

Reputation: 26060

Because C++ syntax doesn't allow this. You need to instantiate your static variable outside of the scope of some function.

Besides you forget a semicolon ; after your class ending bracket.

Upvotes: 3

Related Questions