C++ Namespace is a declarative area that gives the names of the types, functions, variables, etc. inside of it as a scope. When you were first starting to learn the C++ language, you might have noticed a common line which was “using namespace std” in all your basic applications. This is because the entire library is defined in its own namespace called std. Declaring std, gives you direct access to the names of the functions and classes within the C++ library, without having to insert each one with std::.

As you eventually reach an advanced level of understanding of C++, you may not want to declare the standard C++ library by inserting “using namespace std” if your code will only be using a small amount of the library otherwise it would cause name conflicts during compiling. But if your code has several references to library names, then it’s beneficial to declare the std library.

Purpose of c++ Namespaces 

In simple terms, C++ Namespace is used to organize code by localizing the name of variables in order to avoid name collisions which is useful for large projects. An example would be if you had a program where you defined a class Overflow and a library used in your program contains a class called Overflow as well. This would lead to problems in compiling as there is a conflict with the names because both names are stored in the global namespace. The compiler has no way of knowing which version of the Overflow class is referring to within your code. If we were to create a separate namespace for each Overflow class, the program would have no conflicts with the name of the class.

Creating your own c++ Namespaces example

 

#include <iostream>
using namespace std;
 
// first name space declaration
namespace first_space
{
void display_line()
{
cout << "Inside first namespace" << endl;
}
}
 
// second name space declaration
namespace second_space
{
void display_line()
{
cout << "Inside second namespace" << endl;
}
}
 
int main() {
 
// Calls function from first name space.
first_space::display_line();
 
// Calls function from second name space.
second_space::display_line();
 
return 0;
}
Share this post

FAQ's

What are Namespaces in C++?

C++ Namespace is a declarative area that gives the names of the types, functions, variables, etc. inside of it as a scope.

What is the Purpose of Namespaces?

C++ Namespace is used to organize code by localizing the name of variables in order to avoid name collisions which is useful for large projects.