skydoor
skydoor

Reputation: 25878

why using directive in C++ is not encouraged?

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!

Upvotes: 13

Views: 5526

Answers (4)

cuteCAT
cuteCAT

Reputation: 2311

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.

Upvotes: 0

James
James

Reputation: 25533

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

Upvotes: 5

zmbush
zmbush

Reputation: 2810

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.

Upvotes: 5

Yaakov Shoham
Yaakov Shoham

Reputation: 10548

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.

Upvotes: 3

Related Questions