Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we declare static variable in a class & the definition in outside of the class?

Tags:

c++

We declare a static variable in a class and initialize the variable outside the class, but we use the variable within the function.

Anyone tell me the reason why? Thanks in Advance

like image 978
Vicky Avatar asked Dec 10 '13 07:12

Vicky


2 Answers

I'm not sure but my guess is, because inside a class member variables are only declared. They are initialized through a constructor or other member functions.

This happens when an object is instantiated. However for static members, the objects need not be instantiated. Hence they need to be initialized once outside of the class.

EDIT:
Actually it is not necessary to initialize the static variables, but it is necessary to define them outside the class to allocate memory for them. Only after their definition, can they be initialized and then used in the program.

like image 105
Abhishek Bansal Avatar answered Sep 22 '22 13:09

Abhishek Bansal


Because static variables need to have some storage allocated somewhere.

Let's take this for example:

struct Example
{
    static int counter;
    Example() { counter++; }
};

You can create as many Example instances as you want, but there will only ever be one Example::counter variable. It's basically a global variable in disguise. But where should it live? Back in the early days of C++, Stroustrup decided the solution to this was for you to explicitly choose one translation unit (i.e. .cpp file) and declare it there, just as you would a "real" global variable. So you need to do something like

// Only in one .cpp file
int Example::counter = 0;

(Of course, later on templates were invented, and weak symbols to go with them, which could have solved this awkward mess, but it was too late by then.)

like image 29
Tristan Brindle Avatar answered Sep 22 '22 13:09

Tristan Brindle