0
Posted February 1, 2011 by Spyros in C/C++ Programming
 
 

How and Why to Use Namespaces in C++

hello-my-name-is
hello-my-name-is

Namespaces is a very useful C++ feature. The important thing to understand is that namespaces are nothing more than a way to name certain variables, functions, classes and more data structures inside a certain scope name. What does this mean ? Think of a simple example. You happen to use two user defined libraries that you include in your main program. While this is just a matter of 2 includes, you get a compilation error of a multiple declaration. What is happening ? Well, if each library happens to contain a class named as “String”, you would be getting a compilation error for declaring the same class twice. This is exactly the problem that namespaces solve.

Remember the “using namespace std” that we use when including the iostream library to our c++ code. This defines that we use the std namespace, inside which cout, cin and more are included. It would be easy to create your own version of cout in a namespace of your own and include that instead of the standard library one.

Let’s now take a look at a simple example to further understand how namespaces are used :


#include <iostream>
using namespace std;

namespace equals3
{
    int a = 3;
}

namespace equals4
{
    int a = 4;
}

int main()
{
    cout << equals3::a << endl;
    cout << equals4::a << endl;
    return 0;
}

You see that 2 different namespaces are used here. Each own contains its own variable that is initialized with a different integer value. In our main program, we just print the 2 different variables, using the scope operator(::) to define the namespace that is used. If you execute this program, you will get a printout of “3 4”. You could also be using something like “using namespace equals3”, that would actually define that a is an integer variable having a value of 3 in our scope (till main() ends). Notice that the namespaces do not define the actual variable itself. Therefore, you could just as easily redefine “int a=5;” in your program. What they do is that once you use the variable a somewhere in your code, the namespace gets recognized and a is now an integer having a value of 3.


Spyros