Trusted answers to developer questions

What are namespaces in C++?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Namespaces allow entities like classes, objects, and functions to be grouped together under one name. This way, the global scope is divided into “narrower” scopes that are identifiable by name.

Namespaces are created in C++ as follows:

namespace myNamespace {
   int a;
}

To call the namespace-enabled version of a function or a variable, prepend :: to the function or variable’s name:

myNamespace :: a;

The functionality offered by namespaces is very useful in cases where redefinition of functions, variables, or classes, is a risk. The examples below highlight this functionality:

Using the :: syntax

#include <iostream>
using namespace std;
namespace first
{
string str = "I am from the first namespace.";
}
namespace second
{
string str = "I am from the second namespace";
}
int main ()
{
cout << first::str << endl;
cout << second::str << endl;
return 0;
}

You may have noticed that using namespace std;is used in several C++ codes; this is because all the files in the C++ standard library declare all of their entities within the std namespace. Therefore, by using the std namespace, we are able to use all of the iostream functions without attaching std:: before them. Theusing keyword is just an alternative to using ::.

Using the using keyword

#include <iostream>
using namespace std;
namespace first
{
string str = "I am from the first namespace.";
}
namespace second
{
string str = "I am from the second namespace";
}
int main ()
{
/*
'using namespace' has validity only in the block in
which it is stated or,
in the entire code (if it is declared globally).
This is why both namespaces made below are also
made in seperate blocks using {}.
*/
{
using namespace first;
cout << str << endl;
}
{
using namespace second;
cout << str << endl;
}
}

RELATED TAGS

namespace
c++
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?