Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

including (STL) header files in a header [duplicate]

Tags:

c++

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?

like image 906
Daan Timmer Avatar asked Dec 20 '25 16:12

Daan Timmer


1 Answers

... 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:

  • http://www.gotw.ca/gotw/034.htm
  • https://stackoverflow.com/a/10290176/1463922

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...

like image 68
PiotrNycz Avatar answered Dec 23 '25 04:12

PiotrNycz