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
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.
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.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With