Namespaces act as a scope/grouping around declarations (named types, variables, functions, etc.) to prevent name collisions and help organise code.
To create a namespace:
namespace GroupA {
int var = 1;
void foo() {}
}
Then access the members of the namespace with the scope operator (::):
GroupA::var;
GroupA::foo();
Namespaces can be nested:
namespace GroupA {
namespace GroupB {
int bar = 2;
}
}
namespace GroupC::GroupD {
int car = 3;
}
GroupA::GroupB::bar;
GroupC::GroupD::car;
You can bring the members of a namespace into global scope with the using directive:
using namespace GroupA;
Which lets you access those members without the scope operator:
var;
foo();
Warning
Avoid using namespaces (in header files especially) since this pollutes the global scope which can cause name collisions.
Dan