Static functions can only access static data
Why must static member variables be initialised outside the class?
A static variable belongs to the class, not to an object. If it were initialised inside the class, every new object of the class would reset it to the initial value, which could unexpectedly undo what other objects intended by operating on that static variable
However,
static const int a = 1;
can be initialised inside the class, because const means the variable never changes, so the data in the static memory block is the same for every object
Why can't static members be initialised inside the class?
In C++, a static member of a class must be declared inside the class and initialised outside it, like this:
class A
{
private:
static int count ; // declared inside the class
};
Defined and initialised outside the class, without repeating the static keyword
int A::count = 0 ;
Or it can just be defined without an initial value, but whether the default is 0 probably depends on the compiler?Defined only, without an initial value; the default value depends on the compiler
int A::count;
Why?Because a static member belongs to the whole class rather than to any particular object. Initialising it inside the class would mean every object contains that static member, which is a contradiction.
Without int A::count = 0 ; // variable definition, compilation will fail with an “undefined reference to ‘A::count’” error. This is because the static member variable count has not been defined, i.e. no memory has been allocated for it yet, so it obviously cannot be accessed.