Dis possible?

Hi there, I just created an account so I am a bit unfamiliar with the rules and such but I'll try my best, also I am 14 and from Sweden so my English might be a bit off.

So basically my question is this:

If I have main.cpp, class.h and class.cpp. Someone told me to #include as little as possible in my class.h and instead do that in my class.cpp file. Why is this and how can I do it? So I created a string in class.h called "mystr" and now I wanna #include <string> in class.cpp alone without getting an error message.

I don't know if it's possible, please tell me if it is and if so how!

/Sigge aka the really newb guy.
If you need to use the name std::string anywhere in the header, the header file needs to have #include <string>

The entities in the C++ standard library are defined in headers, whose contents are made available to a translation unit when it contains the appropriate #include preprocessing directive. - IS

http://eel.is/c++draft/using.headers


23. Make header files self-sufficient.

Summary
Behave responsibly: Ensure that each header you write is compilable standalone, by
having it include any headers its contents depend upon.

Discussion
If one header file won't work unless the file that includes it also includes another
header, that's gauche and puts unnecessary burden on that header file's users.
... But don't include headers that you don't need; they just create stray dependencies.

Alexandrescu and Sutter in 'C++ Coding Standards: 101 Rules, Guidelines, and Best Practices'

Someone told me to #include as little as possible in my class.h and instead do that in my class.cpp file. Why is this and how can I do it?

For your own files the risk is that you create a circular dependency. A.h includes B.h and B.h includes A.h. This would not work. If you include as little files as possible (use forward declarations when necessary) you'll seldom run into this problem.

When including headers of other libraries the benefits of this practice are less obvious but reduced compile times is one. It also helps reducing the amount of extra stuff that gets included when your header is included. This is not a huge problem with the standard library because it puts most things in the std namespace but if you include a C library that puts everything in the global namespace (even worse if they use macros) it could interfere with code that wasn't expecting those extra names to be included.
Last edited on
Topic archived. No new replies allowed.