According to OO concept, you should NEVER use global static variables.
You can instead define a static variable in your class for the instance count of your class.
Make it private, so that no one else except your constructor can increase the count.
Provide a public function to get the counter. See example below:
yourclass.h:
class YourClass {
private:
static int instanceCount_;
public:
YourClass() {++YourClass::instanceCount_;} // constructor
~YourClass() {--YourClass::instanceCount_;} // destructor
static int instanceCount() {return instanceCount_;}
};
yourclass.cpp:
int YourClass::instanceCount_ = 0;
As far as the concept of static / global / global static / extern
1. static:
1a) global static:
A static variable form like it below:
static int numberOfPersons;
This kind of variable can only be seen in a file (will not have name collision with other same variable name in other files)
1a) class static: (already has an example in the instance count above)
A class may have static members, which are visible to that class (accessed only by Class::Var form) only (instead of 'file only' as said above). It will not have name collision with same variable name in other class. It only has one copy per class (not per instance).
1b) Both global static and class static are global. (since they can be globally accessed, either with class qualifier "Class::" or not.
So, 1a. and 1b. explains static, global, and global static, er, partially, see 2. below
Another form of global variable, is just define a variable without 'static', like it below:
int numberOfPersons;
Without 'static', this variable can be seen by other file, using 'extern' keyword. And it will have name collision with the same variable in other file. So, globally, you can only define it ONCE across all your source files.
extern: declare a variable/function which is defined in somewhere else. It is normally seen in a header file. As said in 3., you can have some variables defined in other file, and declare this variable as extern, like below, in another source file which uses it.
extern int numberOfPersons;
int addPersonCount()
{
numberOfPersons++;
}
Hope this helps.