Scenario:
foo.h:
#include <vector>
class foo {
public:
std::vector<int>* getVector();
/* ... other methods declarations ... */
}
foo.cpp:
#include "foo.h"
#include <vector>
/* ... other methods definitions using std::vector ... */
std::vector<int>* foo::getVector() {
return new std::vector<int>();
}
I want .cpp to be independent of any possible future changes in the header. If for whatever reason the interface of the class changes and the dependency from <vector> can be eliminated, I risk that other methods in the .cpp also lose that inclusion.
Is it correct to repeat the inclusion of <vector> in both the .cpp and .h? Does this practice make sense or should I just rely on the inclusions made in the header?
Include what you need, and nothing more.
Including the same header file across multiple .h files and multiple .cpp files is not a problem in itself. Header guards are effective at mitigating problems from including files multiple times.
If you start trying to avoid including the same file multiple times, it can actually be negative as it usually leads to a “mega-include file” which includes everything you need in the entire project. This is bad, because one change to any header file causes everything to re-compile.
If you are worried about a .h/.cpp file both including the same file, then follow these guidelines: