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
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With