Namespaces in C++
Namespaces allow to group entities like classes, objects and functions under a name. This way the global scope can be divided in “sub-scopes”, each one with its own name.
The format of namespaces is:
namespace identifier { entities }
Where identifier is any valid identifier and entities is the set of classes, objects and functions that are included within the namespace. For example:
namespace myNewNamespace { int a; }
The keyword using is used to introduce a name from a namespace into the current declarative region.
Example
// using namespace example #include <iostream> using namespace std; namespace first { int x = 5; } namespace second { double x = 3.1416; } int main() { { using namespace first; cout << x << endl; } { using namespace second; cout << x << endl; } getchar(); return 0; }
Output
5 3.1416
In our program whereas we use cout, cin we used std::cout and std::cin, this is also way to access namesapces, and we can also do it by using keywork like this :
Example
#include <iostream> using namespace std; // system namespace int main() { cout << "hello using namespace"; getchar(); return 0; }
Output
hello using namespace