According to Why can't I multi-declare a class
class A
; is a declaration while
class A { ... }
is a definition
Typically, in header files, we define the class and we implement its member functions in the .cpp
. But wouldn't defining classes in the header file violate the One Definition Rule?
According to https://www.learncpp.com/cpp-tutorial/89-class-code-and-header-files/
Doesn’t defining a class in a header file violate the one-definition rule?
It shouldn’t. If your header file has proper header guards, it shouldn’t be possible to include the class definition more than once into the same file.
Types (which include classes), are exempt from the part of the one-definition rule that says you can only have one definition per program. Therefore, there isn’t an issue #including class definitions into multiple code files (if there was, classes wouldn’t be of much use).
While the first part is obviously true, header guards will prevent multiple definitions in the same file, but I am confused about the second part of the answer that addresses my question.
If a header file has a definition of a class, for example ThisClass
, and that header file is included in two other files for example a.cpp
and b.cpp
. Why wouldn't it violate the One Definition Rule? If a ThisClass
object is created in either file, which definition would be called?