C++ Class Design – Defining Classes in One or More Files

cclassclass-design

When creating a C++ class what is best practice>

  • Put the entire class definition and member functions in a header file
  • Put the class definition and function declarations in the header file and put the function definitions in a separate source file
  • Put the entire class definition and declare member functions in a source file?

I realize you can do it any of those three ways, but I am wondering if there is a preferred/fastest way. Any information would be great.

Best Answer

It depends, as usual.

Generally, it's best practice to split each class into a header (.h or .hpp) and source (.cpp) file, where you put everything you can in the source file*, because it considerably speeds up building your program. This is incredibly important in real world development because large projects can take anywhere from 15 minutes to several hours to fully recompile and link. If you change anything in a source file the compiler only needs to recompile that cpp file into an object file and link the programs that include this object file. If you change anything in a header file, the compiler needs to recompile all cpp files that include that header and link all the programs that include any of these object files.

If the class is lightweight and very unlikely to change it's usually better to have it all in a header file. An example would be a class that serves as a strongly typed ID and only has a constructor and a comparison operator. Using only a header file keeps the code simpler and easier to read, and in this special case doesn't harm compile time because the class will "never" change.

If the class is a template it is usually not possible to put anything in a cpp file (unless we use template specialization), but it is often convention to place the definitions below the class declaration in the header file, using the inline keyword to allow compilation.


*You can put even more in the source file if your project suffers strongly from header dependencies and the resulting compile time: pImpl Idiom