Possible Duplicate:
reincluding header in implementation
What I am wondering is that it is common practice to not use using namespace xxx in a header file as not to pollute the global namespace.
How does this go for #includes?
If I have foo.h and foo.cpp.:
//Foo.h
#ifndef FOO_H_
#define FOO_H_
#include <string>
class Foo
{
public:
Foo(std::string * a, std::string * b);
virtual ~Foo();
};
#endif /* FOO_H_ */
//Foo.cpp
#include <string>
#include <Foo.h>
Foo::Foo(std::string * a, std::string * b)
{
// TODO Auto-generated constructor stub
}
Foo::~Foo()
{
// TODO Auto-generated destructor stub
}
Would I really need to #include <string> in both files? Would including it only in the .h or .cpp suffice? (I know both will work, but what is advisable?)
edit, a bit more background information regarding my question.
If I would be using certain classes in my header file (either as variables or method arguments) I would forward declare them in the header file and only include the header file itself in the source file. But this will not work for most STL libs because you can't forward declare class-templates?
... because you can't forward declare class-templates?
class templates can be forward declared - like non template classes:
// forward declaration
template <typename T>
class C;
However, as @AlexandreC stated in comments, for std::string it would be quite complicated, because std::string is typedef from template <typename,typename,typename> basic_string;.
I write it would be complicated, if it would be allowed. And it is not allowed, see:
According to the C++11 standard, 17.6.4.2.1:
The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified.
So, no choice but include <string> in header file for std::string.
For your main question - I would include in source and header files, unless I was pretty sure it would be always included in header file and never removed...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With