What is Namespaces?
Namespaces : The basic purpose of Namespaces is to reduce name clashes that occur with multiple, independently developed libraries. It can be defined as a declarative region that can be used to package names, improve program readability, and reduce name clashes in the global namespace. They facilitate building large systems by partitioning names into logical groupings.
namespace school
{
class UpperKG
{
};
class LowerKG
{
};
void Admit()
{
}
// Other code in the namespace
}
- Consider another example where two namespaces contain same name :
namespace A
{
int x = 3;
int z = 4;
}
namespace B
{
int y = 2;
int z = 4;
}
int add()
{
int sum;
sum = A::x + B::z;
return sum;
}
- Here, the scope resolution operator (::) specifies the namespace from where variable z is to be used. Another way of achieving this is ‘using’ directive as follows :
int add()
{
using B::z;
using A::x;
int sum = x + z;
return sum;
}