Creating and Using Namespaces 643
18
DOuse namespaces instead of static
global variables.
DON’Tapply the statickeyword to a
variable defined at file scope.
DO DON’T
Creating a Namespace ........................................................................................
The syntax for a namespace declaration is similar to the syntax for a structor class dec-
laration: First apply the keyword namespacefollowed by an optional namespace name,
and then an opening curly brace. The namespace is concluded with a closing brace but
no terminating semicolon.
For example:
namespace Window
{
void move( int x, int y) ;
class List
{
// ...
}
}
The name Windowuniquely identifies the namespace. You can have many occurrences of
a named namespace. These multiple occurrences can occur within a single file or across
multiple translation units. When this occurs, the separate instances are merged together
by the compiler into a single namespace. The C++ Standard Library namespace,std, is a
prime example of this feature. This makes sense because the Standard Library is a logical
grouping of functionality, but it is too large and complex to be kept in a single file.
The main concept behind namespaces is to group related items into a specified (named)
area. Listings 18.6a and 18.6b provide a brief example of a namespace that spans multi-
ple header files.
LISTING18.6A Grouping Related Items
0: // header1.h
1: namespace Window
2: {
3: void move( int x, int y) ;
4: }