Namespaces allow grouping variables, functions, and types under a name, preventing name conflicts between different parts of the code or libraries.
Definition and usage
namespace group {
int var1 = 10; // Variable in the group namespace
}
namespace another_group {
double var2 = 2.3; // Variable in the another_group namespace
}To access variables from a namespace, use the namespace:: prefix:
auto variable1 = group::var1;
double variable2 = another_group::var2; // Access variable from another namespaceUsing namespace
Allows using variables from a namespace without the prefix:
using namespace group; // Use variables from group namespace without the group:: prefix
int var3 = var1; // var1 from the group namespaceNote
std(from the standard library) is a namespace. Types likestd::string,std::vector, orstd::coutuse thestd::prefix precisely because of this.
Warning
Avoid overusing
using namespacein large programs: it can cause ambiguities when two namespaces define the same name.
Next: Exceptions and Errors