Does namespaces in header file effects cpp files?

Let's say I have a foo.h

1
2
3
4
5
6
7
8
9
10
11
12
#ifndef thingie
#define thingie

#include <string>

using namespace std;

class Foo{
    public:
        Foo();
};
#endif 



and this is my yolo.cpp

1
2
3
4
5
6
#include "Foo.h"
#include <iostream>

Foo::Foo(){
    string crap;
}



my questions is, do I have to put namespace std; in my yolo.cpp?

also, if I include iostream in my yolo.cpp and my Foo.h already namespaced std, do I need to namespace std in my yolo.cpp?
When you #include something, I believe that's equivalent to just putting the content of that file on that line. So yes, anything you declare, and anything like using, #define, etc is also gonna be like that in the .cpp file that includes a .h file.

If you included iostream in the header already, you don't need to include it in the .cpp anymore.

Hope that answers it!
Hi,

It is a very good idea not to have using namespace std; anywhere in your code.

Have a read of the posts in this topic.

http://www.cplusplus.com/forum/beginner/142171/#msg750664


Just put std:: before each std thing.

It is also a good idea not to have #define in your code. Make them const variables ( not global) instead.

Header Guards are OK though.

Hope all is well :+)
Last edited on
If you included iostream in the header already, you don't need to include it in the .cpp anymore.

Strive to the opposite; the less dependencies you have in the headers, the better.

That foo.h.
* Line 4 should not be there any more than the line 6, because there is no std::string in the class definition. The client code that includes 'foo.h' will implicitly include 'string' and all the headers that 'string' includes, even though the client code doesn't even have to know about the existence of std::string in order to use class Foo.

Similarly, the shown yolo.h does not use anything from 'iostream' and thus should not include it. The yolo.cpp has to know the definition of identifier 'string' that is on line 5.

See http://herbsutter.com/2013/08/12/gotw-7a-minimizing-compile-time-dependencies-part-1/
Topic archived. No new replies allowed.