C++ Coding Style – Forward Declaration vs Include

ccoding-style

Reduce the number of #include files in header files. It will reduce build times. Instead, put include files in source code files and use forward declarations in header files.

I read this in here. http://www.yolinux.com/TUTORIALS/LinuxTutorialC++CodingStyle.html.

So it says if a class (class A) in header file does not need to use the actual definition of some class (class B). At that time we can use the forward declaration instead of including the particular (class B) header file.

Question: If the class (class A) in the header if doesn't use actual definition of a particular class (class B), Then how forward declaration helps to reduce the compile time?

Best Answer

The compiler does not care if class A uses class B. It only knows that when class A is compiled and it has no prior declaration of class B (forward declaration or otherwise), it panics and marks it as an error.

What is important here is that the compiler knows you didn't try to compile a program after your cat walked on your keyboard and created some random letters which may or may not be interpreted as a class.

When it sees an include, to be able to use any information contained within, it must open the file and parse it (regardless of whether or not it actually needs to do so). If that file then includes other files, those too must be opened and parsed, etc. If this can be avoided, it is generally a good idea to use a forward declaration instead.

Edit: The exception to this rule being precompiled headers. In this case, all headers are compiled and saved for future compilations. If the headers don't change, the compiler can smartly use the precompiled headers from previous compilations and thus cutting down compile times, but it only works well if you don't often need to change headers.