We have been defining variables in different scopes in c++ programs, such as classes, function, blocks, etc. ANSI C++ Standard has added a new keyword namespace to define a scope that could hold global identifiers. The best example of namespace scope is the C++ Standard Library. That is why we have been using the directive
The using namespace statement specifies that the members defined in std namespace will be used frequently throughout the program.
using namespace std;
The using namespace statement specifies that the members defined in std namespace will be used frequently throughout the program.
Defining a Namespace
We can define our own namespace in our programs. The syntax for defining a namespace is similar to the syntax for defining a class. The general form of namespace is:
namespace namespace_name
{
// Declaration of
// variables, function, classes, etc.
}
Example:
namespace TestSpace
{
int m;
void display(int n)
{
cout<<n;
}
} // No semicolon here
Here, the variable m and the function display are inside the scope defined by the TestSpace namespace. If we want to assign a value to m, we must use the scope resolution operator as shown below.
TestSpace::m=100;
Note that m is qualified using the namespace name.
This approach becomes cumbersome if the members of a namespace are frequently used. In such cases, we can use a using directive to simplify their access. This can be done in two ways:
using namespace namespace_name; // using directive
using namespace_name::member_name; // using declaration
In the first form, all the members declared within the specified namespace may be accessed with-out using qualification. In the second form, we can access only the specified member in the program.
Example:
using namespace TestSpace;
m=100; // OK
display(200); // OK
using TestSpace::m;
m=100; // OK
display(200); // Not ok, display not visible