In general, should class appear in .h file (sort of like normal function prototype style) and then the .cpp file would #include the .h file OR should class just be directly defined in the .cpp file?
Just wondering, seen codes do either but which is better / recommended / preferred and why?
You also can keep the class completely in the header file as many header-only libraries do.
In this case they are much easier to integrate in a project.
If you want to put the class in a.dll or .lib file you need to create a separate .cpp file.
If you don't need to show something to everyone, keep it to yourself.
So prefer to define your classes in the source file, where they won't pollute the rest of the program.
It's about interfaces: the header file should describe an interface that the source file (usually) implements and emphasize the structure of the program - i.e., the header files might logically segregate modules or sub-systems.
If the implementation of that interface uses some code internally, that internal code shouldn't be mentioned in the header file, because it's irrelevant to the interface the header is intended to describe. Indeed, names that aren't part of the interface should be given internal linkage, where possible.
There are also mechanical benefits. Additional code in header files:
- slows compilation of all the TUs (source files) which include the header
- introduces extra names into all of the TUs which include the header.
- makes the file harder to read
If you're writing templates, or you're trying to write a header-only library, you'll perhaps need to put the implementation in a header file, hopefully inside a details namespace.