Possible Duplicate:
Defining static members in C++
I am working little bit on C++, and I don't understand how to use static fields in C++, they seem useless. Please correct me.
I cannot do that:
class AClass{
public:
static int static_field = 0;
};
AND THAT does not work either
class AClass{
public:
static int static_field;
};
int main(){
int AClass::static_field = 0;
return 0;
}
@heksesang: Yes, it happens only in this constellation. If I make both A and B static libs or both shared libs, I do not face the issue (c'tor of A is run only once).
The only way to initialize static final variables other than the declaration statement is Static block. A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.
When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name. Static variables are initialized only once.
3) Static variables (like global variables) are initialized as 0 if not initialized explicitly.
Try this:
class AClass{
public:
static int static_field;
};
int AClass::static_field = 0;
int main(){
return 0;
}
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