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



What Is Namespace in C++?

Namespaces provide a scope for identifiers (variables, functions, etc.) within their declarative region. Namespaces are used to systematize code in logical groups, preventing naming conflict, 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. An Using tells the compiler that the following code uses names in an identified namespace. The program shows 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 the first namespace.
    fun();
}

Output:

This is the first NS


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram