Lesson content
Read, practise, then check your understanding
Namespaces group related names without adding runtime cost. Definitions can be split across files, and nested namespace syntax keeps large libraries organized.
namespace learning::math {
constexpr double pi{3.141592653589793};
double area(double radius) {
return pi * radius * radius;
}
}
namespace lm = learning::math;
double result = lm::area(2.0);
A namespace alias shortens a long qualified name. An unnamed namespace gives declarations internal linkage within one translation unit, a modern alternative to file-scope static for implementation details.
using declarations and directives
using std::string; imports one name into a scope. using namespace std; imports candidates broadly and can create collisions or change overload resolution. Never place a using-directive in a public header, because it affects every includer. Limited declarations inside a function may be reasonable.
Argument-dependent lookup also searches namespaces associated with function arguments. It enables idioms such as using std::swap; swap(a, b);, allowing a type-specific non-member swap to be found. Inline namespaces support API versioning while exposing one version as if it belonged to its parent. Choose namespace names that are stable, specific, and owned by the project; do not add declarations to std except narrow customizations explicitly allowed by the standard.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.