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:
::
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
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 inwhich it is stated or,in the entire code (if it is declared globally).This is why both namespaces made below are alsomade in seperate blocks using {}.*/{using namespace first;cout << str << endl;}{using namespace second;cout << str << endl;}}
Free Resources