Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

According to Static data members on the IBM C++ knowledge center:

The declaration of a static data member in the member list of a class is not a definition. You must define the static member outside of the class declaration, in namespace scope.

Why is that? What's the schematic behind that regarding the memory allocation?

like image 914
henryyao Avatar asked Sep 11 '13 18:09

henryyao


People also ask

Why static data members are needed to be declared in the class?

When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present.

Why definition of static data member is necessary?

The reason for this is simple, static members are only declared in a class declaration, not defined. They must be explicitly defined outside the class using the scope resolution operator. If we try to access static member 'a' without an explicit definition of it, we will get a compilation error.

Can static member function be defined outside the class?

Static member functions can also be defined outside of the class declaration. This works the same way as for normal member functions.


2 Answers

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.

like image 95
Mike Seymour Avatar answered Oct 01 '22 10:10

Mike Seymour


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.

like image 40
UpAndAdam Avatar answered Oct 01 '22 10:10

UpAndAdam