Namespaces in C++

Posted

When you were first starting to learn the C++ language, you might of 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. By declaring std, it 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 advance level understanding 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 its beneficial to declare the std library.

Purpose of Namespaces

In simple terms, namespaces in C++ are used to organise code by localising 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 Overflow class are 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 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