Moule Lin
← All notes

C++ Notes: Static Members

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
};

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.