C++

One Definition Rule (ODR)

Classes/structs and non-inline functions cannot have more than one definition in the entire program.

Template and types cannot have more than one definition by Translation Unit.

Is one class per file really necessary?

The term here is Translation Unit and you really want to (if possible) have one class per translation unit ie, one class implementation per .cpp file, with a corresponding .h file of the same name.

It’s usually more efficient (from a compile/link) standpoint to do things this way, especially if you’re doing things like incremental link and so forth. The idea being, translation units are isolated such that, when one translation unit changes, you don’t have to rebuild a lot of stuff, as you would have to if you started lumping many abstractions into a single translation unit.

Also you’ll find many errors/diagnostics are reported via file name (“Error in Myclass.cpp, line 22”) and it helps if there’s a one-to-one correspondence between files and classes. (Or I suppose you could call it a 2 to 1 correspondence).

Source: StackOverflow

  • Ahh, so it’s the same argument as why it’s better to have separate implementations, see Compiler