Presenting the Problem
Suppose you are designing a custom string class that is used in a large-scale project. This means that dozens of other classes and modules will depend on the header file in which the string class is defined. Here's a slightly contrived implementation of this class for demonstration purposes:
//+++ file String.h
//..copy ctor et al.
std::size_t length() const;
std::ostream & operator << (std::ostream& s) const;
std::vector <char> vc;
Lock lck; //multithreading support
Each client that uses this class has to #include
the header String.h
. The problem is that whenever you change the private section of this class, every piece of code that uses this class has to be recompiled. Not only does this dependency increase compilation time considerably, it also compromises encapsulation.
Remove Redundant #includes
String.h #includes three other headers. The first two are known to take relatively long to compile because they are made up of several other internal headers and template code. Notice, however, that String.h contains only declarations of its member functions. Therefore, you don't really need the bulky <iostream> header to compile it. Replace it with the lightweight header <iosfwd>. Since String.h is #included in multiple source files, the overall effect can be noticeable.
Is it possible to remove <vector> and Lock.h as well? Yes, it is.