Learn C++
#include "advanced/namespaces.hpp"

Namespaces in C++

//concept

Namespaces partition the global name pool so libraries coexist: std::vector vs boost::vector never collide because the qualifier disambiguates. Every standard name lives in std precisely so user code owns the unqualified ground.

using namespace std; in a header sprays thousands of names into every includer — banned by every style guide. Prefer full qualification, targeted using-declarations (using std::string;), or namespace aliases (namespace fs = std::filesystem;) for long nests. Anonymous namespaces give file-local linkage, the modern static.

//how it works
1

Qualify to disambiguate

std::sort vs my::sort coexist peacefully — the :: prefix selects exactly which entity is meant.

2

Never using-directive in headers

using namespace std; at header scope forces itself on all includers transitively — keep it out of headers, period.

3

Targeted using-declarations

using std::string; imports one name into the current scope — convenience without the collision blast radius.

4

Aliases and anonymous

namespace fs = std::filesystem; shortens deep nests; anonymous namespace { ... } hides helpers per translation unit.

//example
#include <iostream>
#include <string>
 
namespace app {
std::string tag = "v1";
void show() { std::cout << tag << std::endl; }
}
 
int main() {
app::show();
return 0;
}
Output
v1
1tag and show live inside app, invisible to unqualified lookup from outside.
2app::show() qualifies the call explicitly — no using-directive needed.
3v1 prints from the namespaced variable, collision-free by construction.
//use cases
Library code that must never collide with user or third-party names
Versioning APIs as v1::/v2:: namespaces coexisting in one binary
Shortening deep nests with aliases at function or file scope
Hiding translation-unit helpers in anonymous namespaces

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.