0

Why can classes have multiple definitions across translation units but not functions even when the function definitions are identical? My idea is that the reason for this can be one of two things: it goes against some compiler/linker enforced design principle, or it causes an actual technical error when compiling and linking.

I can maybe understand why this would be a design principle error. It would be irresponsible to have the same function with the same params and different definitions defined in multiple places, but why should an error be thrown for functions that are identical in every way but defined in multiple places? These same qualities could be had by a class and no linking error would occur. Is this some consequence of how classes and functions are handled differently internally or what?

Don't be scared to get as technical as you'd like. I probably wont feel comfortable moving on from this nagging question unless I have a full answer anyway.

JaMiT
  • 14,422
  • 4
  • 15
  • 31
Baybird
  • 1
  • 1
  • 2
    I suspect there's a terminology mistake happening here, specifically "definition". Can you [edit] your question with a basic example of the multiple definitions of the same `class` that you think is fine? – Stephen Newell May 22 '23 at 02:10
  • 2
    You can in fact have multiple identical definitions of a function... as long as the function is marked `inline`! (In fact, functions defined inside classes are implicitly `inline` specifically in anticipation that the class definition will be repeated). – HTNW May 22 '23 at 02:44
  • See dupe [Doesn’t defining a class in a header file violate the one-definition rule?](https://stackoverflow.com/questions/59535478/why-can-classes-be-defined-in-header-files) or see [Why does defining functions in header files create multiple definition errors, but not classes?](https://stackoverflow.com/questions/68186806/why-does-defining-functions-in-header-files-create-multiple-definition-errors-b) – Jason May 22 '23 at 03:01
  • 1
    Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to search and then research and you'll find plenty of related SO posts. – Jason May 22 '23 at 03:04
  • @StephenNewell `class foo;` is a *declaration*. `class foo {};` is a *definition*. So, yes, having multiple definitions of classes is the norm and is fine (if they are in different translation units and are identical). – j6t May 22 '23 at 06:19
  • Yes classes and functions are handled differently. A class does not have an address, but a function does. Things that have addresses (statically, that is, before program execution begins) are handled by the linker, while things that do not have addresses are not. This is a simplistic explanation that doesn't take into account inline functions and templates and whatnot, but one must start somewhere. – n. m. could be an AI May 22 '23 at 20:19

0 Answers0