Namespaces

August 12th, 2009 by carlos


A namespace is a feature that allows classes and functions to be created in a restricted scope, that is, accessible only using the name of the namespace as a qualifier for identifiers.

Namespaces exist to simplify the task of giving names to classes and functions. In C, all structs and functions are in the global namespace (unless they are made static). This means that it is very possible that a clash may happen between methods or structs defined in different libraries.

The most common method used to solve this problem in C and earlier versions of C++ was creating prefixes. For example, if a group developed a library called YZ, they would prefix all symbols define by this library with the YZ_ prefix. Therefore, this would prevent a clash with other symbols defined in different libraries.

Modern languages avoid this problem by making all code part of a module, where definitions of symbols are maintained. Symbols can only be referenced by importing a module, according to the rules of the language. For example, Java has packages, C# has assemblies, and Python has modules.

In C++, namespaces are not required, but are strongly encouraged for new development. Using namespaces means that there are less opportunities for clashes with software that was written by other people.


Examples

Here is an example of how to define a namespace called “Example”:

namespace Example {
  class A {
   void test();
  }
}

Code can be added to a namespace by simply using the namespace block as show above:

namespace Example {
void A::test() { std::cout << " a test \n"; }
}

To use a class defined in a namespace, you can refer to the fully qualified name (namespace + class name):

void test2() {
   Example::A a = new Example::A();
}

The second possibility is employing the using clause:

using namespace Example;
void test3() {
   A a = new A();
}