In all of your programs this semester, you have include the
compiler directive using namespace std;. What exactly
is a namespace, why do we include this statement?
What's a Namespace?
Since different programmers may work on the same project, it's possible
that they will use the same name for two different things (class, function, etc).
Namespaces provide a way of grouping the names created by each programmer.
A namespace is a collection of class names, variable names, function names
and other name definitions.
It's possible to include more than one namespace in your program.
The scope of a namespace is limited by the block of code in which it is used, the same
as for variables. However, if the same name is defined
in multiple namespaces in the same block, a compiler/linker error will occur.
Suppose that we plan to use the function named f which is defined
in the namespace Fred. There are three ways to make the function f
available to your code.
Many authorities prefer the 2nd method listed above, inserting all statements like this
at the top of your file. This method doesn't include unused names from
the namespace which might cause potential conflicts, documents what names are being used from each
namespace and doesn't clutter your code by always qualifying your names. The downside is that
this list of names must be maintained as new names are used or old ones removed.
- As we have done this semester, we can insert a using directive into our code
using namespace Fred;
Not only does this make the function f known to the compiler, it also makes all names in
- We can specify that we only want to use f from namespace Fred by inserting
- We can omit any using directive and always qualify the function name when it's used by writing
instead of just
Creating a Namespace
To create a namespace of your own, let's call it CMSC202, place code, class definitions,
etc. in a namespace grouping as in
// some functions, classes, etc
You can create as many namespace groupings for CMSC202 as you want,
(even in different files) and all will be considered part of the same namespace.
We can then insert using namespace CMSC202; into our code to make our names known to the compiler.
More on Namespaces
See section 11.2 of the text for more details on namespaces including the "global namespace"
and "unnamed" namespaces.
Last modified: Mon Dec 6 12:47:42 EST 2004