Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I cannot initialize static field in C++ [duplicate]

Tags:

c++

static

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;
}
like image 411
Yoda Avatar asked Aug 10 '12 15:08

Yoda


People also ask

Can we initialize static variable twice?

@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).

How do you initialize a static field?

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.

Can we're initialize static variable in C?

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.

Are static variables always initialized to zero in C?

3) Static variables (like global variables) are initialized as 0 if not initialized explicitly.


1 Answers

Try this:

class AClass{
    public:
        static int static_field;
};

int AClass::static_field = 0;

int main(){
    return 0;
}
like image 51
Code-Apprentice Avatar answered Oct 22 '22 04:10

Code-Apprentice