Using Namespace

Hey again!

I'm following Accelerated C++ and for the starting code, it has you writing 'std::cout' for instance, later on it has you defining 'using std::cout'.

How come it doesn't just use 'using namespace std' instead of defining them individually?
closed account (zb0S216C)
By stating using namespace std, you're telling the compiler that you'll be using everything within the std namespace. However, by stating using std::cout, you're telling the compiler that you're using cout from std, and nothing else, so there's no need to qualify cout with std::.

Here's a close analogy: There's 3 cars in your garage (you're a bank manager): Bentley Continental GT, Ferrari Enzo, and a Pagani Zonda. The garage is the namespace, and the cars are: cin, cout, and string respectively. When you say using Garage::Ferrari Enzo, you're saying: "I'm using the Ferrari Enzo, but not the others".

NerdTastic just reminded me of this: By using namespace std, you effectively defeat the purpose of namespaces.

Wazzak
Last edited on
The reasoning behind it is that the std namespace is huge, and by using only a single command it cuts down on space. I think. I haven't read up on it in a while.
So in essence, it makes your program more efficient to just define the ones you want, rather than having them all?
Last edited on
closed account (zb0S216C)
Yes, and it retains the purpose of namespaces.

Wazzak
More efficient? It doesn't affect runtime performance at all.

The problem is more that it brings many symbols into the global scope and the standard headers are allowed to include other headers so you can't really know what's being included. This increases the risk of name clashes.

I also think that prefixing with std:: everywhere makes the code easier to read because you can see directly that it's a standard identifier.
Let's say that I've written the following
1
2
3
4
5
6
7
8
9
10
11
#include <algorithm>
using namespace std;

template<class T> void reverse(T& x, T& y) { T c(x); x = y; y = c; }

int main()
{
    int a = 2;
    int b = 3;
    reverse(a,b);
}


I've included <algorithm> because I had some code later that uses functions from it. Now I've declared using namespace std; so that means that ALL of the functions in <algorithm> are available. Unfortunately there is a std::reverse() function. This means that we have no idea which function will be called, ours or the one in <algorithm>. My compiler gives me an "Ambiguity" error but I'm not sure if all compilers do this.

By declaring using std::cout; or something similar, we can avoid including EVERYTHING in std. Another was to resolve this ambiguity is to do std::reverse(); or ::reverse(); in our code. This specifies if our function is in the std namespace or in a global scope.
Topic archived. No new replies allowed.