
Namespaces address the problem of naming conflicts between different pieces of code. For example,
you might be writing some code that has a function called fun(). One day, you decide to start using
a third-party library, which also has a fun() function. The compiler has no way of knowing which
version of fun() you are referring to within your code. You can’t change the library’s function
name, and it would be a big pain to change your own.
Namespaces come to the rescue in such scenarios because you can define the context in which
names are defined. To place code in a namespace, enclose it within a namespace block. For example,
the following could be the contents of a file called namespaces.h:
namespace example {
void fun();
}
The implementation of a method or function can also be handled in a namespace. The fun()
function,for instance, could be implemented in namespaces.cpp as follows:
#include <iostream>
#include "namespaces.h"
void example::fun()
{
std::cout << "fun() called in the example namespace" << std::endl;
}
Or:
#include <iostream>
#include "namespaces.h"
namespace example {
void foo()
{
std::cout << "fun() called in the example namespace" << std::endl;
}
}
Since we have provided our version of example namespace so it will not interfere with the function provided by third party and thus we can use it without name conflict using namespace.
To call the namespace, we have to use namespace::functionname –> example::fun()
Any code that falls within a “example” namespace block can call other namespace within the same namespace without explicitly prepending the namespace. This implies namespace is useful in making the code more readable. You can also avoid prepending of namespaces with the using directive.
This directive tells the compiler that the subsequent code is making use of names in the specified namespace. The namespace is thus implied for the code that follows:
#include "namespaces.h"
using namespace example;
int main()
{
fun(); //calls example::fun()
return 0;
}
I hope you find this article useful.