C++ Concept Map

Namespaces

The idea of a namespace is to allow re-use of names across collections of files so that programmers are free to choose names which might already be in use, perhaps in an imported library file. This is especially true of standard libraries, where there are many commonly-used names. It is another form of encapsulation, but this time (unlike the class encapsulation) it is merely considered to be a collection of names. To use it, preface a collection of declarations and/or definitions with the namespace declaration:

namespace myNamespace {

class C { ... };

class D { ... };

}

where myNamespace is any identifier. All of the names declared are then considered to be part of that namespace. Additional files can have the same (or a different) namespace by using a similar namespace declaration, and there could be more than namespace in a file. All the names (classes, functions, templates, variables) must now be prefixed with the namespace when used outside the namespace:

namespace ns1 {
int var;
}


namespace ns2 {
void f() {
  cout << ns1::var << endl;
}
}

This is the way that the standard template library can be used:

#include <iostream>
int main () {
   std::cout << "Hello world in ANSI-C++\n";
   return 0;
}

More common is to avoid all these prefixes with the 'using' command:

#include <iostream>
using namespace std;
int main () {
   cout << "Hello world in ANSI-C++\n";
   return 0;
}

Please mail any corrections and/or suggestions to Roger Hartley at
rth@cs.nmsu.edu

Copyright © 2003 Roger Hartley