I started programming in C++ about 6 months ago and started off like many, structuring projects in a C like way. I split .cpp (implementation) and .hpp (header) files and used virtual classes for interfaces.

As I have learned more I've realised that the majority of C++ code I've seen is making very extensive use of templates. It seems that cpp files are rarely used, as they don't play well with templates. Moreover I have read that code in header files (and thus templates) are more heavily optimizable by the compiler (I guess because they can be 'seen' from everywhere). It's even to the extent that some projects I have seen have separate header files for the same templated code, splitting over definition and implementation.

My question is, disregarding compile times, is there ever a reason not to just exclusively use templates and header files for non-test code (I suppose also except for main.cpp)? Is this the commonly accepted modern c++ style?


1 Answer 1


To answer your literal question: technically, there are two reasons for using cpp files (and not just header files):

  1. Decreased compiled times (which you cannot disregard when you are ever going to write a bigger C++ program).

  2. The possibility of providing a library in a compiled, binary form to third parties, where except the header files no source code has to be exposed.

For a more extended explanation about the trade-offs between "header-only" code and using "cpp" files, please read my former answer to the question Are header-only libraries more efficient?. Though the asked question was not exactly the same, I guess my answer there applies to your question as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.