Where "include" in C++

I'm reading some C++ code and notice that there are "#include" both in the header (.hpp) files and source (.cpp) files. I guess if I move all the "#include" in the file, "foo.cpp", to its' header file "foo.hpp". Then let "foo.cpp" only one line of #include "foo.hpp", the code should work anyway taking no account of issues like drawbacks, efficiency, and etc .

I guess that my "all of sudden" idea must be in some way bad, but what could be the exact drawbacks of it? I'm new to C++, and I may need to read lots of C++ reference books to figure out.

Thanks in advance.


  • As a rule, put your includes in the .cpp files when you can, and only in the .h files when that is not possible.

    You can use forward declarations to remove the need to include headers from other headers in many cases: this can help reduce compilation time which can become a big issue as your project grows. This is a good habit to get into early on because trying to sort it out at a later date (when its already a problem) can be a complete nightmare.

    The exception to this rule is templated classes (or functions): in order to use them you need to see the full definition, which usually means putting them in a header file.