Namespaces
While we have largely ignored the topic to date,
the use of namespaces is the defined standard for C++.
Namespaces essentially allow the program to define program segments in which
different names are visible: for instance we might have one version of an
initialize() routine that we want visible in some parts of the program,
and another version of initialize() that we want visible in other
parts of the program.
Creating and extending namespaces
To create a namespace,
the programmer first creates the name spaces which contain the declaration
and definition of the desired variables or routines, and then specifies at different
points in the program which versions should currently be used.
The syntax for creating namespaces is quite similar to that for structs:
namespace SomeNameForTheSpace {
// the variables and routines defined within the space
};
For example, if I had an initialize() routine I wanted to use in
a debugging context, I might create a namespace like
namespace DebugSpc {
void initialize()
{
// code for DebugSpc::initialize
}
};
To add to the namespace later I simply use the same syntax:
namespace DebugSpc {
// any new things I want to add ...
};
If I had another initialize() routine, I might create another namespace:
namespace NormalSpc {
void initialize()
{
// code for NormalSpc::initialize
}
}
Using namespaces
There are three main ways to use a routine or variable associated with
a particular namespace:
- Explicitly identify both the object and space
This is done by giving the name for the namespace, followed by two colons,
followed by the name of the item.
For example, assuming we had included whatever file
contains the definition of the namespace,
we could call a specific initialize routine using either
DebugSpc::initialize();, or
NormalSpc::initialize();
- Specify which routine you associate with an identifier
For example, if we wanted to just write initialize()
and have the compiler/linker know we mean the version from DebugSpc
then we can explicitly say we are using that version:
using DebugSpc::initialize();
From this point on, if we say initialize(); we actually
get the debug version.
- Specify that we want everything from a specific namespace
to be available for direct use, e.g.:
using namespace NormalSpc;
specifies that we want to be able to directly call anything from
the NormalSpc namespace.
Ambiguities
You can specify that you are "using" as many namespaces (or parts thereof)
as you like, but if there is a name conflict/ambiguity then your program
may be unable to link and run.
In the example above, an ambiguity would be generated by the following:
using namespace DebugSpc;
using namespace NormalSpc;
initialize();
The std namespace
The most common namespace use you will observe is the following
using namespace std;
The std namespace is defined to cover the use of the C and C++
standard libraries (e.g. iostream, string, cmath, etc).