Why is there no multiple definition error when you define a class in a header file?

The one-definition rule (3.2, [basic.def.odr]) applies differently to classes and functions:

1 – No translation unit shall contain more than one definition of any variable, function, class type, enumeration type, or template.

[…]

4 – Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program […]

So while (non-inline) functions may be defined at most once in the whole program (and exactly once if they are called or otherwise odr-used), classes may be defined as many times as you have translation units (source files), but no more than once per translation unit.

The reason for this is that since classes are types, their definitions are necessary to be able to share data between translation units. Originally, classes (structs in C) did not have any data requiring linker support; C++ introduces virtual member functions and virtual inheritance, which require linker support for the vtable, but this is usually worked around by attaching the vtable to (the definition of) a member function.

Leave a Comment