Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include in header files

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?

like image 287
thetux4 Avatar asked May 22 '11 13:05

thetux4


2 Answers

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.

like image 111
Puppy Avatar answered Oct 11 '22 13:10

Puppy


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.

like image 42
Jesse Emond Avatar answered Oct 11 '22 14:10

Jesse Emond