About Namespace

Is there any situation where you would want to use option 2 instead of option 1?

option 1) using namespace std;

option 2) using std::cout;
Yes.
1
2
3
4
5
6
7
8
9
10
#include <iostream>

using namespace std;

int main() {
   int cin;
   // cin >> cin; //Whoops!
   std::cin >> cin; //Here you still need the prefix, so why bother confusing yourself
   ...
}

I usually use "option 2" in files without a main function and when not in global scope, as to be more careful.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

namespace my_ns {
   using std::ostream;

   class T {
      ...
   };

   ostream& operator<<(ostream &out, const T &t) {
      ...
   }
}
Ideally, no one should ever name a variable or class with the same name as something in the standard library. With that said, you still shouldn't count on other people to not make mistakes.
closed account (z05DSL3A)
using declarations and the using directive have subtle differences
See: http://www.cplusplus.com/forum/beginner/9181/#msg42419
Intrexa wrote:
no one should ever name a variable or class with the same name as something in the standard library.
Isn't that the point of of namespaces, so that you can use the same names in different spaces.
To be honest, I don't really use either. Mostly I just type the std::
closed account (z05DSL3A)
To be honest, I don't really use either. Mostly I just type the std::

Full name qualification is usually best.

Restricting the scope of using declarations and using directives is also better than just dumping them in global scope.
closed account (zb0S216C)
My rule of thumb: Only use what you need. Put simply, I use Option #2.
Full name qualification is usually best.

Usually, yes - except when dealing with the std namespace.
Fully qualifying names in the std namespace has little practical advantages, but is a tremendous waste of time.
Topic archived. No new replies allowed.