Previous      Up      Previous     Course Home   e-mail

2.6 What is a namespace?

At an informal level, a namespace is the set of all names that have been declared at some point in a program.

Often, programmers will #include a header file in order to use just one or two names decalred in that header. But because the header file actually declares dozens or maybe hunders of other items, all of those names become part of the programmer’s namespace. This effect is sometimes called namespace pollution.

The problem with namespace pollution is that it increases the odds that the programmer might accidentally choose a variable or function a name that is already declared in a header somewhere and has been, unbeknownst to the programmer, found its way into the namespace. The result of such a namespace collision is usually an error message, and often a fairly unintelligable one at that.

Even worse, in large programs a programmer might be trying to use headers from two different commercial libraries. If these two libraries try to use the same name for anything, the resulting namesapce collision would force the programmer to choose between the two libraries.

For these reasons, the C++ standardization committee introduced the C++ namespace as a way to control namespace pollution. A namespace is a “container” of names. Every library is supposed to use its own namespace and only to declare things within that namespace. This includes the C++ standard library, hwere everything is declared within the namesapce std. Declaring things within a namespace is easy:


namespace MyCS361Library {
int foo ();
const int bar = 21;
};
There are three ways to get access to a name that has been declared within a namespace:
  1. Put the namespace name in front, connected by “ :: ”. E.g.,

    void baz ( int & i )
    {
    i = i + MyCS361Library :: bar - MyCS361Library :: foo ();
    }
  2. Use a “using declaration” to make a single name from the namespace visible:

    void baz2 ( int & i )
    {
    using MyCS361Library :: bar ; // makes bar visible
    i = i + bar - MyCS361Library :: foo ();
    }
  3. Use a “using directive” to make everything declared in a namespace visible:

    void baz2 ( int & i )
    {
    using namespace MyCS361Library ; // makes foo and bar visible
    i = i + bar - foo ();
    }

 Previous      Up      Previous     Course Home   e-mail