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 here!
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 <iosfwd> 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 <iosfwd> 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 <sstream> to header file instead <iosfwd> 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 <iosfwd> the preprocessed file is 1229 lines while with straight include to <sstream> 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..):
If you liked the story, please press the ❤ button below (did you know that you can give more than one clap). Also please feel free to share this story!
I am Heikki Hellgren, Software Expert and technology enthusiast working at Elektrobit Automotive. My interests are in software construction, tools, automatic testing and all the new and cool stuff like AI and autonomous driving. You can follow me on Medium and Twitter and check out my websitefor more information.