class A{ private: std::string id; public: void f(); }; gives compile time error. However, if I include <string> at top, it compiles correctly. I don't want to use include statements in headers,though. How can i do it?
Including headers in other headers is a completely necessary thing. It's wise to reduce it as much as possible, but fundamentally, if your class depends on std::string, then you have no choice but to #include <string> in the header. In addition, there's absolutely nothing wrong with depending on any and/or all Standard classes- they are, after all, mandated to be provided on any implementation. It's using namespace std; that's frowned upon.
You must include <string> in this case to be able to use std::string.
The only moment when you can avoid #including a header is when you're only using references or pointers of the object in your header. In this case you can use forward declaration. But since std::string is a typedef, you can't forward declare it, you have to include it.
I'm sure you're trying to follow the advice to try to #include as less as possible, but you can't follow it in this case.
`).You can make sure all dependencies are met by including the necessary files in the implementation files before including your other header files, i.e. make sure #include <string> appears on the first line in your implementation file (.cpp) before including your own header file.
This is not exactly best practice. All header files should fulfill their own dependencies, so users of the header file do not need to care about dependencies. At least that is my humble opinion.
Unfortunately you can't get around it.
Even if your class definition looked like this:
class A { private: std::string* id; public: void f(); }; then there's still not much you could do, as forward declaring std::basic_string<char, etc> is a pain in the ass. I'm not even going to demonstrate.
Fortunately, although using namespace std in headers is a definite no-no, you can usually get away with #includeing standard headers in your own headers, without worrying about it.
Possibly some crazy extern declaration would help, but that's not a way. Why don't you want to include in header files?
using namespace std and similar. You can include any header file in your header ant it won't cause any trouble.extern, but that's never a way. I have no idea if can you achieve the same thing with classes in C++, however that sounded reasonable for me.