Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use static variable C++

I got a little confused of the usage of static / global / global static / extern variables.

I would like a counter variable to get increased in any creation of a class instance.

Would highly appreciate if someone can post a clarification of the appropriate usage for each.

like image 349
yael aviv Avatar asked Sep 16 '14 10:09

yael aviv


1 Answers

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 created as given: static int numberOfPersons;

This kind of variable can only be seen in a file (will not have name collision with other variable having same name in other files)

1b) 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::VarName syntax) only (instead of 'file only' as said above). It will not have name collision with variables of same name in other class. It only has one copy per class (not per instance).

1c) Both global static and class static are global(since they can be globally accessed, either with class qualifier Class:: or not.

So, 1a., 1b. and 1c. partially explain static, global, and global static

  1. Another form of global variable, is just define a variable without static
    syntax: int numberOfPersons;

Without static, this variable can be seen by other file, using extern keyword. And it will have name collision with the variables having same name in other files. So, globally, you can only define it ONCE across all your source files.

  1. extern: Declare a variable/function which is defined in somewhere else. It is normally seen in a header file. We 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.

like image 142
Robin Hsu Avatar answered Sep 24 '22 16:09

Robin Hsu