Why does a static data member need to be defined outside of the class?

It's a rule of the language, known as the One Definition Rule. Within a program, each static object (if it's used) must be defined once, and only once.

Class definitions typically go in header files, included in multiple translation units (i.e. from multiple source files). If the static object's declaration in the header were a definition, then you'd end up with multiple definitions, one in each unit that includes the header, which would break the rule. So instead, it's not a definition, and you must provide exactly one definition somewhere else.

In principle, the language could do what it does with inline functions, allowing multiple definitions to be consolidated into a single one. But it doesn't, so we're stuck with this rule.


As of C++17 you can now define static data members inside a class. See cppreference:

A static data member may be declared inline. An inline static data member can be defined in the class definition and may specify an initializer. It does not need an out-of-class definition:

struct X {
     inline static int n = 1; 
};

It's not about the memory allocation piece at all. It's about having a single point of definition in a linked compilation unit. @Nick pointed this out as well.

From Bjarne's webite https://www.stroustrup.com/bs_faq2.html#in-class

A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.

Tags:

C++

Static