tags:

views:

368

answers:

4

Hi

I read that using directive is not encouraged in C++ saying never put using directives in header files. Why is it like that? Any hint for me?

Thanks!

+3  A: 

Because it can break working code, when trying to add your header, if your header namespace trample other namespace that defined in the past-working code.

Y. Shoham
+2  A: 

If you are talking about the 'using' directive, the reason for not using it is because if you say

using namespace std;

in a header file, all files that #include that header will be forced to use that namespace, and that could cause problems.

zipcodeman
No, they won't be forced to use that namespace.
anon
"This isn't an argument, it's just contradiction!"
struppi
@struppi mynamespace::foo = 1
anon
@Neil: Sorry, I don't get it. Putting "using namespace baz" into a header imports all symbols of baz into all scopes which include that header. In a sense this could mean "to be forced to use that namespace", don't you think?
struppi
No, because I can choose to use other namespaces, per my previous comment.
anon
Well, you can't "choose" to use your symbol in that qualified way, you _have_ to do so, only because you #include'd a header that used a using directive. That's pretty selfish of that header, don't you think, just to save some typing?
struppi
+1  A: 

using namespace x; is a very bad idea, since you have no idea what names you are importing, even with the standard library.

However: using std::cout; and similar statements are a very good idea, because they import symbols explicitly, and make code more readable (though it still might not be a good idea to put them in the global scope in header files).

Autopulated
who cares what names you import, the compiler errors if there's an ambiguity...
Inverse
@Inverse, not only you make names visible, but the names are visible as part of a much wider scope enclosing both the using directive but also the namespace that it specifies. The names are explicitly not imported into the scope where the directive appears. So ambiguities with much more names are possible.
Johannes Schaub - litb
A: 

It is similar to no to declare static variables in header files. Adding using statement in header files will bring the namespace into .cpp files that include the header file. It is not necessary. In the worse case, you may have to change some variable or functions names in .cpp in order to avoid naming conflicts.

Sherwood Hu