Multiple namespaces


1.  Multiple namespaces

So far we have covered the std namespace declaration, the random namespace declaration. In this post we will talk about the multiple namespace declaration. Many of your programs will need a multiple namespace declaration. You can have multiple namespace declarations of a namespace with a given name, and the contents of all namespace blocks with a given name within the same namespace. For example, you might have a program file with few namespaces like this:

namespace sortStuff
{
// Everything in here is within sortStuff namespace
}
namespace calculateStuff
{
// Everything in here is within calculateStuff namespace
// To refer to names from sortStuff they must be qualified
}
namespace sortStuff
{
// This is a continuation of the namespace sortStuff
// so from here you can refer to names in the first sortStuff namespace
// without qualifying the names
}

A second declaration of a namespace with a given name is just a continuation of the first, so you can reference names in the first namespace block from the second without having to qualify them. They are all in the same namespace. Of course, you would not usually organize a source fi le in this way deliberately, but it can arise quite naturally with header fi les that you include into a program. For example, you might have something like this:
#include < iostream > // Contents are in namespace std
#include "myheader.h" // Contents are in namespace myStuff

#include < string > // Contents are in namespace std
// and so on...
Here, iostream and string are ISO/IEC C++ standard library headers, and myheader.h represents
a header fi le that contains our program code. You have a situation with the namespaces that is an exact parallel of the previous illustration. This has given you a basic idea of how namespaces work. There is a lot more to namespaces than I have discussed here, but if you grasp this bit, you should be able to fi nd out more about it without difficulty, if the need arises.
Share on Google Plus