7

Possible Duplicate:
Why is 'using namespace std;' considered a bad practice in C++?

I've seen some code examples where people use, say, std::cout whereas in other places people will have using namespace std; at the top for simplicity instead. Which is generally preferred?

Community
  • 1
  • 1
Emir
  • 481
  • 1
  • 5
  • 15
  • 2
    Another alternative is `using std::cout`. – hmjd Aug 15 '12 at 14:14
  • 6
    [Why is `using namespace std;` considered a bad practice?](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-a-bad-practice-in-c) – chris Aug 15 '12 at 14:14
  • 3
    If you want a simple rule: Don't use `using` directives, ever (i.e. `using namespace abc;`); and use `using` declarations (e.g. `using Base::foo`) only for unhiding and ADL control. Do use namespace aliases to keep the source code tidy, though. – Kerrek SB Aug 15 '12 at 14:16
  • Personally, I always use `using namespace std;`, because even if it is "bad practice", it makes my code much cleaner. And if I'm a good OO programer, I wont be polluting the global namespace with my own functions and classes that have the same names as std classes. If you need to make your own class called `string`, you probably have some thinking to do about your application design. – Linuxios Aug 15 '12 at 14:20
  • I would say never use it. If you do, you will regret it one day. If you you know **all** the names in the `std` namespace and all the ones that will come in future standards, then OK, maybe use it in very local scopes deep inside implementations. In which case it probably doesn't bring you any benefits anyway. – juanchopanza Aug 15 '12 at 14:58

3 Answers3

3

Use std::cout to avoid any potential name clashes. If you use using using namespace std; you will populate your global namespace with all the std name which might conflict with classes or function names you or someone else in your team have written. This is well explained in the C++ faq lite and in SO

Community
  • 1
  • 1
tiguero
  • 11,477
  • 5
  • 43
  • 61
2

I personally use the full namespace denomination when writing code, e.g. std::string, etc. It makes things clearer for anyone who reads that, which function the developer wants to use.

I've seen the following saying:

write it once, read it a thousand times...

:)

Derek
  • 1,104
  • 13
  • 35
fduff
  • 3,671
  • 2
  • 30
  • 39
0

First note that you should never using namespace in a header - you may already be aware of this. The reason is that it will bring the using into any source files that include it.

Even at the source file level I prefer to explicitly qualify standard library functions and classes liek std::cout. However in some cases I will use specific using instead for convenience (using std:endl for example). I generally prefer the explicit qualification however.

Mark B
  • 95,107
  • 10
  • 109
  • 188