Question

C++ forces the programmer to define a non-constant static member outside the class, and the reason for this that I keep seeing is that if the static member was defined inside the class, this would result in multiple definitions for the static member. I understand that having multiple definitions for a static member is bad, but I don't understand where these multiple definitions would even come from. Shouldn't an initialized non-constant static member just go in the data section and that be the only definition?

struct Student {

   static int x = 4; // Why would this result in multiple definitions?

};

Also, I read in this other stackoverflow post that const static members are simply inlined into the code wherever it is used: Why can't I have a non-integral static const member in a class? Is that handled by the preprocessor along with all the other directives? ( I will ask this in another post if needed, but I wasn't sure if it's worthy of a separate post ).

Était-ce utile?

La solution

It would happen because/when your header gets included in multiple "translation units" (think .cpp files).

Each TU will then contain a copy of the definition.

At link time, they will clash. (The linker links the objects from each translation unit)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top