Skip to content

Chapter 22 of 31

Namespaces

Organize APIs, avoid collisions, use aliases, and understand lookup and ADL.

28 minutes 10 quick checksBy Subha Prasad
Lesson 22 of 31Course navigation

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.

What problem do namespaces solve?
What does std::vector mean?
Why avoid using namespace std in headers?
What is an unnamed namespace used for?
What does a namespace alias provide?
Can a namespace be reopened?
What is a nested namespace shorthand?
What is argument-dependent lookup?
Where should a using declaration usually be kept?
May user code add arbitrary declarations to std?

0 of 10 checks passed

Your progress is saved on this device.

Namespaces | C++ Lesson | Subha Prasad