Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private static declaration and subsequent initialization

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

like image 875
sc_ray Avatar asked Dec 27 '22 21:12

sc_ray


2 Answers

  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.
like image 171
Sergey Kalinichenko Avatar answered Jan 08 '23 12:01

Sergey Kalinichenko


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.

like image 24
chris Avatar answered Jan 08 '23 12:01

chris