Wrox Press C++ Tutorial
With large programs, choosing unique names for all the entities can become difficult. This is particularly true when an application is being developed by several programmers working in parallel, or when a vendor wants to produce a library for sale to third parties. Without some kind of mechanism to prevent it, name clashes become highly likely. This is perhaps most likely in the context of user-defined types, or classes, which we will meet in the next chapter. A namespace is designed to overcome this difficulty.
We first met the concept of a namespace in Chapter 1. Now, we're going to have a look at them in a bit more detail. A namespace is a region within a program that attaches an extra name - a namespace name - to all the entity names within it. Two different namespaces can each contain entities with the same name, but the entities will be differentiated because a different namespace name is attached to each of them. The diagram illustrates two namespaces defined within a single program, possibly within the same source file.
In each namespace, there is a variable defined with the name i, and a function declared with the name max(). However, they each refer to distinct entities, with no possibility of a clash between them. You would typically use a separate namespace name within a single program for each collection of code that encompasses a common purpose. Each namespace would represent some logical grouping of functions, together with any related global variables and declarations. A namespace would also be used to completely contain a unit of release, such as a library.
You are already aware that the standard library is defined within the namespace std. This implies that every external name in the standard library is prefixed with std. For instance, the output stream name is std::cout, so to display the contents of a variable, value, you could write:
std::cout << std::endl << value;
The operator :: here is the binary form of the scope resolution operator, that we saw earlier. The statement above qualifies the names cout and endl - it says to the compiler, "You'll find the definition of these names in the std namespace." Of course, you will immediately appreciate that this is not what we have be doing in the examples so far - this is because we have been adding the following statement to our programs:
using namespace std;
In principle, this using directive allows all the names in the namespace, std, to be used without qualification. Of course, any name that you want to use must appear in a declaration prior to where you want to use it. So in this case, the names in the std namespace that you can use will be those in the standard header files that have been included into the file.
The using directive allows the appearance of your code to be simplified somewhat, and in all our examples so far, that has been our motivation for employing the using directive. However, you need to be cautious when doing this. If you employ the using directive for all your namespaces, it defeats the purpose of using namespaces at all. We will come back to the using directive later in this discussion.
All the programs that we have written so far have used names that we declared in the global namespace. The global namespace applies by default in the absence of a namespace being defined. All names within the global namespace are just as you declare them, without a namespace name being attached. In a program with multiple source files, all the names with linkage are within the global namespace.
With small programs, you can define your names within the global namespace without running into any problems. With larger applications, the potential for name clashes increases so you should use namespaces to partition your code into logical groupings. That way, each code segment will be self-contained from a naming perspective, and name clashes will be prevented.
Of course, you need to know how to declare a namespace, so let's look at that next.
You can declare a namespace with the statements:
namespace myRegion
{
// Code you want to have in the namespace, including
// function definitions and declarations, global variables,
// templates, etc.
}
Note that, at the end of the namespace declaration, there is no semi-colon following the closing brace.
The namespace name assigned here is myRegion. This uniquely identifies the namespace and this name will be attached to all the entities declared within the namespace. The braces enclose the scope for the namespace myRegion, and every name within the namespace scope will have the name myRegion attached to it.
You must not include the function main() within the namespace. The runtime environment expects main() to be defined in the global namespace, so you must always place the function main() outside of all your namespaces.
You can extend a namespace scope by adding a second namespace definition in a file. For example, a program file might contain:
namespace calc
{
// This defines namespace calc
// The initial code in the namespace goes here
}
namespace sort
{
// Code in a new namespace, sort
}
namespace calc
{
// This extends the namespace calc
// Code in here can refer to names in the previous
// calc namespace block without qualification
}
Here, we have two blocks declared as namespace calc, separated by a namespace sort. The second calc block is treated as a continuation of the first. Therefore, functions defined within each of the calc blocks all belong to the same namespace. The second block is referred to as an extension namespace definition, because it extends the original namespace definition. You could have further extension namespace definitions in the file, adding more code within the same namespace.
Of course, you would not usually organize a program file in this way directly. However, if you #include several header files into your program file, and each header file contributes some code to the same namespace, then you effectively have the sort of situation described above. A common example of this is when you #include a number of standard library headers (each of which contributes to the namespace std), interspersed with header files of your own (defined within a different namespace). For example:
#include <iostream> // In namespace std
#include "mystuff.h" // In my namespace calc
#include <string>
// In namespace std - extension namespace definition
#include "morestuff.h"
// In my namespace calc - extension namespace definition
Finally, note that references to names within a namespace from inside the same namespace do not need to be qualified. For example, names that belong to the namespace calc can be referenced from within calc, without the need to qualify them with the namespace name.
Let's take a simple example to illustrate the mechanics of declaring and using a namespace.
We will create a program consisting of two .cpp files. The first will just contain definitions of some consts that we defined earlier, but this time defined within a namespace:
// Data5_08.cpp
// Using a namespace
namespace data
{
extern const double pi = 3.14159265;
extern const int primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
}
Here we have defined pi and primes[] within the namespace data. We will use these variables in another translation unit, which will contain main():
// Ex5_08.cpp
// Using a namespace
#include <iostream>
namespace data
{
extern const double pi; // Variable is defined in another file
extern const int primes[]; // Array is defined in another file
}
int main()
{
std::cout << std::endl
<< "pi has the value "
<< data::pi << std::endl;
std::cout << "The forth prime number is "
<< data::primes[3] << std::endl;
return 0;
}
If you compile and run this it will produce the output:

In the file containing main(), we must declare pi and days[] as external, since they are defined in a separate translation unit. We do this with the statements:
namespace data
{
extern const double pi; // Variable is defined in another file
extern const int primes[]; // Array is defined in another file
}
We have to place the declarations for the external variables within the namespace data, because the variables are defined within this namespace in the first .cpp file. This demonstrates the point that we discussed earlier - that a namespace can be defined piecemeal. Even within a single file, there can be several namespace blocks corresponding to the same namespace name, and the contents of each will be in the same namespace.
As a general rule, you should put these declarations for pi and primes in a header file, data.h say. The contents of this header file would just be:
// data.h
// Declarations for globals in namespace data
namespace data
{
extern const double pi; // Variable is defined in another file
extern const int primes[]; // Array is defined in another file
}
Then, to make the declarations available in the file containing main() (or any other file that needed access to these variables), you would simply need to add an #include directive at the beginning:
#include "data.h"
The name has the extension .h to identify that it is a header file. We'll see this in action in Ex5_09.
The syntax for #include is slightly different here. You should omit the .h extension only when including standard library headers.
Back in Ex5_08, the code in the body of main() just consists of two output statements:
std::cout << std::endl
<< "pi has the value "
<< data::pi << std::endl;
std::cout << "The forth prime number is "
<< data::primes[3] << std::endl;
The function main() is in the global namespace (it must be, otherwise it won't be recognized), so any name used in main() that is declared and defined in another namespace must be qualified - either directly, or implicitly via a using directive (note that there is another way, which we will see in a moment). Since we do not have a using directive for the namespace std in the source file, we must qualify each name that is from the standard library. Thus cout and endl must be qualified with the namespace name std, so that they can be recognized by the compiler. The constants pi and primes are defined and declared within the namespace data, so these names must be qualified too.
In principle, the using directive can make all the names in a namespace available. In the previous example, we could add a using directive for the namespace std, and avoid the necessity of qualifying cout and endl explicitly. The file contents would then be:
// Ex5_08.cpp
// Using a namespace
#include <iostream>
namespace data
{
extern const double pi; // Variable is defined in another file
extern const int primes[];// Array is defined in another file
}
using namespace std;
int main()
{
cout << endl
<< "pi has the value "
<< data::pi << endl;
cout << " The forth prime number is "
<< data::primes[3] << endl;
return 0;
}
Now, we don't need to qualify cout and endl, although we still could if we wanted to. You would need to do this if you had a name of your own that clashed with a name in the standard library namespace. It would be silly to do so, but to illustrate the point you could write:
int cout = 10;
std::cout << Value of variable cout is " << cout;
In this code fragment, there is a variable cout defined here of type int, which is contained in the global namespace. There is also an output stream, cout, but this belongs to the std namespace. In the second line above, cout is understood to refer to the global variable, which effectively masks the output stream cout, even if we have a using directive. You can still get at the output stream cout by using the namespace name as a qualifier, as shown in the second statement.
When you use an unqualified variable name, the compiler will first try to find the definition of the variable in the current scope, prior to the point at which it is used. If it is not found, then it will look in the immediately enclosing scope. This will continue until the global scope is reached. If a declaration for the variable is not found at global scope (which could be an extern declaration), the compiler will conclude that the variable is not defined.
By adding a using directive for the namespace data just before main() in the last example, we could obviate the need to qualify any of the names, so the file contents would be:
// Ex5_08.cpp
// Using a namespace
#include <iostream>
namespace data
{
extern const double pi; // Variable is defined in another file
extern const int primes[]; // Array is defined in another file
}
using namespace std;
using namespace data;
int main()
{
cout << endl
<< "pi has the value "
<< pi << endl;
cout << " The forth prime number is "
<< primes[3] << endl;
return 0;
}
In this case, this makes the code much simpler. If, later, we developed this program so that std and data namespaces both contained a certain name, then we would resolve the ambiguity in the program by using the scope resolution operator. Of course, if there were lots of ambiguities then we'd lose the simplicity of the code again, even with the using directives. An alternative approach, which sits nicely between these extremes, is to use using declarations rather than using directives.
A using declaration declares a specific name from within a given namespace. Each using declaration declares a single name, which can then be used unqualified following the declaration. A using declaration is of the form:
using namespace_name::identifier;
where using is a keyword, namespace_name is the name of the namespace and identifier is the name that we want to use unqualified. Note that this introduces a name from the namespace, which might refer to several different things. For instance, a set of overloaded functions defined within a namespace can be introduced with a single using declaration.
Instead of the using directive for the namespace std in the previous example, we could supply a using declaration for each name that we want to use:
using std::cout;
using std::endl;
These two declarations, preceding the definition of main() in the last example, would allow cout and endl to be used without qualification. Of course, you could also supply using declarations for the constants pi and primes in the namespace data.
Note that although we have placed the using declarations and directives at global scope in all our examples, we can also place them within a namespace, within a function, or even within a statement block. In each case the declaration or directive applies until the end of the block that contains it.
For a function to exist within a namespace, it is sufficient for the function prototype to appear in a namespace. The function can be defined elsewhere, by simply using the qualified name for the function - in other words, the function definition doesn't have to be enclosed in a namespace block. Let's take an example.
Suppose we want to write two functions, max() and min(), to return the maximum and minimum of an array of values. We can put the declarations for the functions in a namespace as follows:
// compare.h
namespace compare
{
double max(const double* data, int size);
double min(const double* data, int size);
}
This could be placed in a header file, compare.h, which would then be #included by any file using the functions.
The definitions for the functions can now appear in a .cpp file. We can write the definitions without enclosing them in a namespace block, as long as the name of each function is qualified with the namespace name. The contents of the file would be:
// compare.cpp
#include "compare.h"
// Function to find the maximum
double compare::max(const double* data, int size)
{
double result = data[0];
for(int i = 1 ; i < size ; i++)
if(result < data[i])
result = data[i];
return result;
}
// Function to find the minimum
double compare::min(const double* data, int size)
{
double result = data[0];
for(int i = 1 ; i < size ; i++)
if(result > data[i])
result = data[i];
return result;
}
We need the compare.h header file to be included so that the namespace is identified. This enables the compiler to deduce that the functions are within the namespace.
Of course you could, if you want, place the code for the function definitions within the compare namespace directly, and you would not have to qualify each function name with the name of the namespace. Therefore, if we were to write the function definitions in this way, we would no longer need to #include the file compare.h.
Using the functions is the same, however you have defined them. To confirm how easy it is, let's try it out with the functions that we have just defined.
The function declarations go in the header file compare.h as we discussed above:
// compare.h
namespace compare
{
double max(const double* data, int size);
double min(const double* data, int size);
}
We will put the definitions for the functions in a separate .cpp file that will contain the following code:
// compare.cpp
#include "compare.h"
// Function to find the maximum
double compare::max(const double* data, int size)
{
double result = data[0];
for(int i = 1 ; i < size ; i++)
if(result < data[i])
result = data[i];
return result;
}
// Function to find the minimum
double compare::min(const double* data, int size)
{
double result = data[0];
for(int i = 1 ; i < size ; i++)
if(result > data[i])
result = data[i];
return result;
}
All we need is a .cpp file containing the definition of main() to try the functions out:
// Ex5_09.cpp
// Using functions in a namespace
#include <iostream>
#include "compare.h"
using compare::max; // Using declaration for max
using compare::min; // Using declaration for min
int main()
{
double data[] = {1.5, 4.6, 3.1, 1.1, 3.8, 2.1};
using namespace std; // Using directive for standard library
const int dataSize = sizeof data/sizeof data[0];
cout << endl;
cout << "Minimum double is " << min(data, dataSize) << endl;
cout << "Maximum double is " << max(data, dataSize) << endl;
return 0;
}
If you compile the two .cpp files and link them, when you run the program it will produce the output:

The declarations for the functions are introduced into the file containing main() with the directive:
#include "compare.h"
If the file compare.h was in a different directory to the source files, then the #include directive must also contain the directory path from the source file to the header file. In this example, the header file compare.h is in the same directory as the source file.
We then have a using declaration for each function, so that we can use the names without having to add the namespace name:
using compare::max; // Using declaration for max
using compare::min; // Using declaration for min
We could equally well have used a using directive for the compare namespace:
using namespace compare;
Since the namespace only contains the functions max() and min(), this would have been just as good, and one less line of code. However, in general the effect of a using directive is quite different from the effect of a using declaration. The using directive allows any name from the namespace that is declared in the file to be used. The using declaration on the other hand only introduces one specific name.
Within main() we first define an array, data, that we will pass as an argument to our two functions:
double data[] = {1.5, 4.6, 3.1, 1.1, 3.8, 2.1};
We then have a using directive for the namespace std that allows us to use the names declared in <iostream> without qualification from this point on:
using namespace std; // Using directive for standard library
We will need to pass the length of the array, data, to each function, so we compute this and store it in the constant dataSize:
const int dataSize = sizeof data/sizeof data[0];
Finally, we call the functions in the output statements which will display the maximum and minimum values from the array, data:
cout << "Minimum double is " << min(data, dataSize) << endl;
cout << "Maximum double is " << max(data, dataSize) << endl;
If we had not written the using declarations for the function names (or a using directive for the compare namespace), then we would have had to qualify the functions in the output statements:
cout << "Minimum double is "
<< compare::min(data, dataSize) << endl;
cout << "Maximum double is "
<< compare::max(data, dataSize) << endl;