Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include std library in header or cpp?

Tags:

If I have a class A which uses iostream, should I put the include statement of iostream in A.h or A.cpp?

like image 396
user695652 Avatar asked Oct 11 '11 22:10

user695652


2 Answers

This is an area of some controversy. My own preference is that each header should be able to stand alone, so if it needs other headers, it includes them. In other words, if client code is going to need to include <iostream> (or whatever) anyway, your header should handle that for them. OTOH, if the user of the iostream is strictly hidden so the client code doesn't need to include it at all, then it should only be included in the implementation file.

In many cases (especially where the header is open to frequent change), you'd prefer to avoid including it in the header. In such cases, the PImpl idiom can be useful to get the dependency out of the header.

If you do need to include <iostream>, do your clients a favor and consider whether you can #include <iosfwd> instead of <iostream> though. This can improve compile time a fair amount.

like image 90
Jerry Coffin Avatar answered Oct 19 '22 22:10

Jerry Coffin


Include it where its needed. If you use something defined in <iostream> in the declaration of the class (like a member variable, a member function parameter or return type, etc), then it should be in the H file. If you only use it in the implementation - then in the CPP.

like image 39
littleadv Avatar answered Oct 19 '22 22:10

littleadv