Static Data Member Initialization

It’s important to distinguish the initializer which says what its initial value is, and the definition. This modified code is valid, with the initializer in the class definition:

class X
{
public:
  int normalValue = 5;
  static const int i = 0;       // declaration, with initializer
};

const int X::i;                 // definition

i.e. What must be outside the class is a definition, not the initialization.

That’s because a variable must have an address in memory (unless it’s only used in limited situations, such as in compile-time constant expressions.)

A non-static member variable exists inside the object it is a member of, so its address depends on the address of the object that contains it. Every time you create a new X you also create a new X::normalValue variable. The non-static data member’s lifetime begins with the class’ constructor. NSDMI syntax doesn’t have anything to do with the variable’s address in memory, it just allows you to provide an initial value in one place, instead of repeating it in every constructor with an explicit constructor initializer list.

On the other hand, a static member variable is not contained within an instance of the class, it exists independently of any single instance and exists from the start of the program, at a fixed address. In order for a static member variable (or any other global object) to get a unique address the linker must see exactly one definition of the static variable, in exactly one object file, and assign it an address.

Because a static variable needs exactly one definition in exactly one object file, it doesn’t make sense to allow that definition to be provided in the class, since class definitions typically exist in header files and are included in multiple object files. So although you can provide an initializer in the class, you still need to define the static data member somewhere.

You can also look at it like declaring an extern variable:

namespace X {
  extern int i;
}

This declares the variable, but there must be a definition somewhere in the program:

int X::i = 0;

Leave a Comment