9

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;
}
Community
  • 1
  • 1
Yoda
  • 17,363
  • 67
  • 204
  • 344
  • `@w00te` and others have already answered the question. I think your confusion arises from the fact that in C++ *declaration* and *definition* are two different things. One makes the symbol visible , the other allocates storage. Do a search on "C++ declaration vs definition" or similar. – David Aug 10 '12 at 16:01
  • Hrm? My answer has the longest timer on it and I don't recall using the word definition anywhere. From MSFT: "Declaration: Is a class name declaration with no following definition, such as class T;." and thats what he has in his second code sample. – John Humphreys Aug 10 '12 at 16:41

4 Answers4

16

Actually, you were close.

You should move: int AClass::static_field = 0; outside of main() so it's global in a CPP file, preferably AClass.cpp.

That way, you declare it in your header and initialize it in your source file. You can use it in main() or wherever else just by doingAClass::static_field after you've got this declaration/initialization set up.

PS: They're definitely not useless.

Here's a good use case... Suppose you are having memory leaks and you need to track them down. You put a static counter in your class, so all instances of that class share it. You then make any constructors/destructors increment and decrement that counter. So, you can print the counter to show how many instances of a class exist to help find your leaks.

John Humphreys
  • 37,047
  • 37
  • 155
  • 255
14

You have to initialize static_field outside main function scope.

int AClass::static_field = 0;
int main(){
}
alvmed
  • 156
  • 5
6

Try this:

class AClass{
    public:
        static int static_field;
};

int AClass::static_field = 0;

int main(){
    return 0;
}
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
4

When you are declaring a static variable here you are stating that there is going to be one instance of this variable shared among all the instances of the class.

Moving the declaration outside of the main function like some of the other answers provided is the correct solution.

Here is some documentation from msdn on the static keyword:

http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx

hope this helps

Brandon
  • 191
  • 2
  • 15