-2

I am currently learning C++ (more precisely C++03) at uni, and I came across the initialization of static members. Non-constant static members should be declared inside the class, but defined outside. Moreover, they also should be declared in source files, not header files. As far as I understand, that is because if you have a myClass.h header with a myClass class in it, and A.cpp and B.cpp which include it, then you can protect yourself from multiple definition inside the same source file with include guards, but you cannot protect from myClass.h being present once in A.cpp and once in B.cpp. If you define the static member inside myClass.h, but outside myClass, then after the preprocess you will have copied the definition of the same thing both inside the global scope of A.cpp and B.cpp. The linker will "see" the global scope of B.cpp from inside A.cpp and vicecersa, so you will have multiple definitions available in a given context, which is a problem.

So my question is, if this is a problem, then how come the definition of the class myClass both in the global scope of A.cpp and B.cpp isn't one?

kesarling He-Him
  • 1,944
  • 3
  • 14
  • 39
Steven P.
  • 1
  • 3

2 Answers2

1

No you misunderstand the reasons. static variables that are not constexpr needs to be initialized only once as it happens at runtime. Something is really wrong if same variable is initialized twice at run-time... Thus they have to be initialized in a .cpp so that compiler/linker knows which library carries it.

Definitions for classes, on the other hand, are compile-time definitions so linker throws away all duplicates. (This is in fact is very bad and results in poor compilation times and at times in ODR issues. Modules C++20 were developed to resolve these issues.).

ALX23z
  • 4,456
  • 1
  • 11
  • 18
0

You've got some concepts wrong, which is all right and happens with everyone. You see, there's no hard and fast rule that the definitions of non-static methods are to be written inside the class. Its perfectly fine even to write them outside the class, the difference being, you then will be able to mask their definitions if you want to, as the header files needs to be provided in cleartext. As against this, if you don't write the functions in a .cpp file, you can't make a library and provide the library, inherently masking the definitions. Also, it is usually recommended to do it the former way, so that the class size in clear text becomes small and the abstraction is better achieved. Also, please do read how to ask a good question on stack overflow.

RE: If you define the static member inside myClass.h, but outside myClass, then after the preprocess you will have copied the definition of the same thing both inside the global scope of A.cpp and B.cpp Please read boilerplate code

Hope this helps. :) And if you don't understand anything, I'm always open for dicussions; don't hesitate to ask

kesarling He-Him
  • 1,944
  • 3
  • 14
  • 39