Forward Declarations and – Hacker Noon

C++ Telltales part 4:

This is fourth part of my C++ Telltales series where I share some tips and tricks to work with C++. Feel free to check out also other parts of the series from my profile!

Forward declarations in C++ are useful to save in compile time as the compiler does not need to check for translation units in the included header. Also it has other benefits such as preventing namespace pollution, allowing to use PImpl idiom and it may even reduce the binary size in some cases. C++ has this cool header which declares forward declaration for all C++ streams such as std::stringstream and std::fstream.

If you have a class that uses any of the stream classes from standard C++, you should use the header in the class declaration and only include the necessary headers in the implementation. See following snippet as an example:

In general you should use forward declarations as much as you can. Changing the to header file instead has tremendous affect on how many lines the compiler has to create in the preprocessing of the file. This can be tested with a simple command:

cat test_class.hpp | g++ -E -xc++ — | wc

This command outputs the test_class.hpp and pipes it to g++ which then outputs preprocessed source code and sends it to the standard output for wc to count the lines. With the the preprocessed file is 1229 lines while with straight include to the same number is 41952. And that’s only if you have one type of streams in use in the class. What a save.

And here is the same image from my first part to get some cover photo for this article (I am still, unfortunately, feeling lazy..):

read original article here