4

A .cpp file has a bunch of class definitions . One class has a private static member as follows:

class SomeClass:public SomeParentClass
{
   private:
     static int count;
};

and right after the class is defined, the count attribute to initialized to zero as follows:

int SomeClass::count = 0;

Coming from the Java/C# world I am having trouble understanding at which point is count initialized to zero? Is it when the SomeClass is instantiated? Also, the class definition has the count type to be int, why does the SomeClass::count has to have an int in front of it?

And my last question is, since the count attribute is private shouldn't its visibility be restricted when it is initialized outside the class definition?

Thanks

sc_ray
  • 7,803
  • 11
  • 63
  • 100

3 Answers3

4
  1. Static members of the class are initialized in arbitrary order upon your program's start-up
  2. The static int count; in the class is a declaration of your static variable, while int SomeClass::count = 0; is its definition. All definitions in C++ require to specify a type.
  3. The fact that the definition of the count appears to have occurred in the file scope, the actual scope of the SomeClass::count remains private, as declared.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

The class static variable will behave as if it is initialized to 0 when the program starts. It is independent of class instantiation.

The C++ language requires a type before an identifier in a declaration.

The C++ syntax to initialize a class static variable makes it look like a global, but access to the variable is enforced during compilation.

jxh
  • 69,070
  • 8
  • 110
  • 193
3
Is it when the SomeClass is instantiated?

No, you can access it via SomeClass::count (assuming the function has rights to SomeClass's private members) before any instantiations. It's fully usable before you start making objects.


Why does the SomeClass::count has to have an int in front of it?

Well, because it's an int. Think of when you make function prototypes and definitions:

int func (int);
int func (int i) {return 1;} //you still need the int and (int i) here
func {return 1;} //NOT VALID - this is what count would be without int

Since the count attribute is private shouldn't its visibility be   
restricted when it is initialized outside the class definition?

Static variable definition is an exception to access specifiers when defined in the normal manner, according to this answer.

Community
  • 1
  • 1
chris
  • 60,560
  • 13
  • 143
  • 205