A self-contained header file is one that doesn’t depend on the context of where it is included to work correctly. If you make sure you #include or define/declare everything before you use it, you have a self-contained header.
An example of a non self-contained header might be something like this:
----- MyClass.h -----
class MyClass
{
MyClass(std::string s);
};
---- MyClass.cpp -----
#include <string>
#include "MyClass.h"
MyClass::MyClass(std::string s)
{}
In this example, MyClass.h uses std::string
without first #including <string>.
For this to work, in MyClass.cpp you need to put the #include <string>
before #include "MyClass.h"
.
If MyClass
‘s user fails to do this he will get an error that std::string is not included.
Maintaining your headers to be self-contained can be often neglected. For instance, you have a huge MyClass
header and you add to it another small method which uses std::string
. If in all places this class is currently used, <string> is already #included before MyClass.h, then someday you will #include MyClass.h as the first header and suddenly you have this new error in a file you didn’t even touch (MyClass.h).
Carefully maintaining your headers to be self-contained helps to avoid this problem.