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

前端 未结 3 1928
粉色の甜心
粉色の甜心 2020-12-09 11:40

I\'m not sure if I asked the question correctly, but let me explain.

First, I read this article that explains the difference between declarations and definitions: htt

3条回答
  •  隐瞒了意图╮
    2020-12-09 11:58

    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.

提交回复
热议问题