Reputation: 4275
If I have a class A which uses iostream, should I put the include statement of iostream in A.h or A.cpp?
Upvotes: 22
Views: 44107
Reputation: 392999
It depends.
If you use the classes in the header file, you need it in the header file (obviously).
If you just use the class declarations you can use incomplete types. In that case, include <iosfwd>
in your header file, and <iostream>
in the cpp
Upvotes: 1
Reputation: 490128
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.
Upvotes: 29
Reputation: 42627
Use it where it is needed.
If your class declaration references types in the header, you will need to include it there. If it's only in the implementation, then you can include it in the cpp file.
Upvotes: 1
Reputation: 20272
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.
Upvotes: 4
Reputation: 30825
Include it in the cpp. That way it's not potentially included in other cpp files that may include your A.h but don't need the iostream. Unless of course for some reason there is something in your header file that needs iostream. But if that's the case you might be doing something else wrong...
Upvotes: 3