If I have a class A which uses iostream, should I put the include statement of iostream in A.h or A.cpp?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With