C++ Namespace

Let's take a situation where there are two students with the same name in an institution.  Then we have to differentiate them in a different manner and more likely we have to add some more information along with their name, like roll number or parents name or email address. The same situation may arise in C++ programming also where you might write some code having function name  i.e. fun() and there is already existing another library having same function name. This makes the compiler halt down and left it with no way to know which of these two function to use within the C++ program. Namespaces are used to solve this situation.

What are Namespaces?

Namespaces provide a scope for identifiers (variables, functions etc) within own declarative region. Namespaces are used to systematize code in logical groups which prevents naming conflict, which can occur especially if there are multiple libraries with single names in your code base. On the namespace scope, all identifiers can be visible for one another without qualification. In brief, the namespace defines a scope.

Defining a Namespace

The keyword namespace is used to define a namespace followed by the name of the namespace. Here is the format:

Syntax:
namespace namespace_name {
// code declarations
}
Example:
namespace salary
{
  int make_money();
  int check_money();
  //so forth....
}

The using Directive

The using directive permits all the names in a namespace to be applied without the namespace-name as an explicit qualifier. Programmers can also avoid pre-awaiting of namespaces with the using namespace directive. Using tells the compiler that subsequent code is making use of names in an identified namespace.

Program showing the use of Namespace in C++:

Example:
#include<iostream> 
using namespace std;

// first name space
namespace firstone {
void fun()
{
    cout << "This is the first NS" << endl;
}
}
// second name space
namespace secondone {
void fun()
{
    cout << "This is the second NS" << endl;
}
}

using namespace firstone;
int main()
{
    // calls the function from first namespace.
    fun();
}
Output:
This is the first NS