Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 988
vrbilgi Avatar asked Jan 15 '11 10:01

vrbilgi


People also ask

Can we initialize static variable inside class?

We can put static members (Functions or Variables) in C++ classes. For the static variables, we have to initialize them after defining the class. To initialize we have to use the class name then scope resolution operator (::), then the variable name. Now we can assign some value.

Can we initialize static variable inside static method?

Static variables in methods i.e. you cannot use a local variable outside the current method which contradicts with the definition of class/static variable. Therefore, declaring a static variable inside a method makes no sense, if you still try to do so, a compile time error will be generated.

Can static variable be used in main?

We cannot declare static variables in the main method or any kind of method of the class. static variables must be declared like a class member in the class. Because during compilation time JVM binds static variables to the class level that means they have to declare like we declare class members in the class.

Are static variables initialized before main?

Global (namespace) variables or static class members 1 live for the entire execution of the program: they must be initialized before main() is run and destroyed after execution finishes.


1 Answers

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?

like image 103
Nawaz Avatar answered Sep 28 '22 09:09

Nawaz