7.3 Namespaces

7.3.1 Do not use using directives

Namespaces are an important tool in separating identifiers and in making interfaces explicit. A using directive, i.e. using namespace, allows any name to be searched for in the namespace specified by the using directive. A using declaration, on the other hand, brings in a single name from the namespace, as if it was declared in the scope containing the using declaration.

#include <iostream>
               
using namespace std; // @@- Non-Compliant -@@
using std::cout;     // @@+ Compliant +@@
               
#include <string>
               
// unqualified name string is looked up in namespace std
// even though the using directive precedes the
// declaration in the translation unit
string foo ();

As pointed out in the example above a using directive will affect all subsequent lookup in the translation unit. For this reason using directives are particularly problematic if used in header files, or occur in the main source file above a #include pre-processor directive. This may lead to ambiguity (compilation error) or maintenance and reuse problems.

References

  • HIC++ v3.3 – 8.2.3

Click here for references