In C++, the keyword using imports symbols from a declared namespace into the current scope. The C++ keyword using can import them either into the global scope or a local scope.

The intent of namespace is to encapsulate a group of symbols together to reduce global namespace pollution. However, it can become cumbersome to need to qualify every reference to a frequenly used namespace, so individual symbols from a namespace (using-declaration) or all the symbols in a namespace (using-directive) can be imported into a compilation unit's scope. If you import all of the symbols from multiple overlapping libraries, this can get messy, obviously. It is not an error to import overlapping symbols, but it is an error to try to use the symbols that actually overlap without a qualification specifying exactly which one you want.

A using-declaration may shadow a variable in an outer scope, but it may not replace a variable in the current scope. The using-declaration brings in all versions of an overloaded function from the namespace.

I have tried to include most of the above in the following example:

namespace one {
void f();
int g();
}

namespace two {
void f();
int g();
int i, j;
}

int j;

void f1()
{
using namespace one;   // bring all symbols from one into local scope
using two::g;   // but override this one (this works only in a function with g++)
g();
}

using namespace one;     // use all of namespace one's symbols in this scope

void two::f();    // implementation of a function in the namespace
{
g();    // uses two::g
}

void f()    // global namespace
{
g();    // uses one::g (from using directive)
}

using two::g;    // bring in duplicate g--not an error (yet)

void ff()
{
int i;
j++;   // global j (::j)
using two::j;   // shadow global variable
j++;   // two::j
// using two::i;   // error -- can't redeclare local variable
// g();   // error--ambiguous use, one::g or two::g ?
two::g();   // qualify to clear up ambiguity
}

For more examples, see namespace.

 

Sources: