![]() |
VOOZH | about |
We have introduced namespaces in below set 1.
Namespace in C++ | Set 1 (Introduction)
Defining a Namespace:
A namespace definition begins with the keyword namespace followed by the namespace name as follows:
namespace namespace_name
{
// code declarations i.e. variable (int a;)
method (void add();)
classes ( class student{};)
}
It is to be noted that, there is no semicolon (;) after the closing brace.
To call the namespace-enabled version of either function or variable, prepend the namespace name as follows:
namespace_name: :code; // code could be variable , function or class.
The using directive:
You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace.
The namespace is thus implied for the following code:
Names introduced in a using directive obey normal scope rules. The name is visible from the point of the using directive to the end of the scope in which the directive is found. Entities with the same name defined in an outer scope are hidden.
Nested Namespaces:
Namespaces can be nested where you can define one namespace inside another name space as follows:
SYNTAX:
namespace namespace_name1
{
// code declarations
namespace namespace_name2
{
// code declarations
}
}
You can access members of nested namespace by using resolution operators as follows:
// to access members of namespace_name2
using namespace namespace_name1::namespace_name2;
// to access members of namespace:name1
using namespace namespace_name1;
In the above statements if you are using namespace_name1, then it will make elements of namespace_name2 available in the scope as follows:
It is also possible to create more than one namespaces in the global space. This can be done in two ways.
5 10
500 501
Unnamed Namespaces
Output:
300