Where to "include" stuff in a class.

When creating and using classes I've always included the stuff the class will need, in the .h (header) file of the class. So for example lets say in one of my functions I output something with the std::cout command, I would include <iostream> inside the header file, so that I could then use it in the .cpp file. Usually the only thing my .cpp (source) file will "include" is the associated header file. But lately I've been looking at other peoples codes and I'll see them include stuff in their .cpp file instead. Is there a rule of thumb to this?
Last edited on
closed account (48T7M4Gy)
A simple way to remember/know what to do is only #include what you need for that file.

Generally only the prototypes go in the header file which works on the principle of data hiding, ie the details are "none of the end users business" and therefore kept separately while the header is made available in clear to read/uncompiled etc form, politeness doesn't come into it.

So the header would generally not have a cout command, that would be in the .cpp file. Thus #include would go in that file not the header.
Last edited on
Alright so you may have some things included in the .h that are not in the .cpp and vice versa. For example if I needed to use a std::string data type in my class I would have no choice but to include <string.h> in the header file, right? So I guess I'm just paraphrasing what you said and making sure I'm clear. Only include in the file what that file needs, in this case <string.h> would NEED to be included in the header file to even create a std::string data type.
closed account (48T7M4Gy)
String was an example I was going to make but it actually is consistent ewith the general principle because, like an int you are declaring a type. int is built-in but string is not so you have to provide the link.

Try it with a class member that is a string declared in the header and used in the implementation file but the #include <string> only in the header.

note that the cpp file has the link via #include "whatever.h"

Alright so you may have some things included in the .h that are not in the .cpp and vice versa.
Yes

For example if I needed to use a std::string data type in my class I would have no choice but to include <string.h> in the header file, right?
See my above comment because it depends where it first appears and the link from the cpp back to the header being included.

So I guess I'm just paraphrasing what you said and making sure I'm clear. Only include in the file what that file needs, in this case <string.h> would NEED to be included in the header file to even create a std::string data type.
Yes, but to convince yourself, try it with a simple test case with a few lines.
Last edited on
Topic archived. No new replies allowed.