CSE 202: Computer Science II, Winter 2018
Namespaces
Using directive

Every entity that makes up the standard C++ libraries is declared inside of the std namespace.

You may have seen "hello world" C++ programs that use the declaration using namespace std;:

#include <iostream> using namespace std; int main() { cout << "hello world" << endl; return 0; }

If the declaration using namespace std; was moved inside the main function, then we can use cout and endl without qualifying them with std:: but only until the end of the main function.

Since using namespace std; was declared in the global namespace, all names within the std namespace will be visible in global scope, accessible from anywhere within the same source file.

A declaration that begins with using namespace is known as a using directive

The using directive can only be used within namespace scope (including global scope) or block scope (such as inside of a function, loop, or if statement). The using directive takes all names from inside a specified namespace and makes them visible as if they were declared in the nearest namespace that encloses both the specified namespace and the using directive.

Study and modify this example to get a handle on how namespaces work:

#include <iostream> using namespace std; namespace A { int i = 2; } namespace B { int j = 3; namespace C { using namespace A; // Makes names in A visible in global namespace until int k = 4, l = 6; // the end of namespace C. } namespace D { int m = 7, n = 8; namespace E { using namespace C; // Makes names in B::C visible in namespace B int o = 9; // until the end of namespace E. } } } void f() { using namespace B::D::E; // Makes names in B::D::E visible in global namespace // until the end of function f. // Names made visible in global namespace are E::o, C::k, C::l, and A::i cout << o << ' ' << k << ' ' << l << ' ' << i << endl; } int main() { f(); return 0; }
Using declaration

The hello world program can also be rewritten as:

#include <iostream> using std::cout; using std::endl; int main() { cout << "hello world!" << endl; }

Instead of a using directive, two using declarations make cout and endl visible in global scope; everything else in the std namespace will still need to be qualified with the scope resolution operator to be used.

A using declaration makes a name accessible within the same scope where this declaration appears.