Imagine two students in the same class are both called Rahul. When the teacher says "Rahul, come here", nobody knows who should stand up. So the class starts saying "Rahul Sharma" and "Rahul Verma" — the surname makes each name unique. Large C++ programs have exactly the same problem: your code, the standard library and three third-party libraries may all want a function called log, count or sort.
A namespace is C++'s surname. You have been using one since your first program: the std in std::cout is the namespace of the C++ standard library. In this chapter you will learn how to create your own namespaces, the different ways of using names from them, why using namespace std; can hurt you, and some lesser-known tools such as unnamed namespaces, inline namespaces and argument-dependent lookup (ADL) — all popular interview topics.
What Is a Namespace?
A namespace is a named scope that groups related declarations (variables, functions, classes, other namespaces). A name declared inside namespace
Nis referred to from outside asN::name, so the same name can exist in different namespaces without conflict.
The operator :: is the scope resolution operator, the same one you used to define member functions outside a class in Classes & Objects. The full name physics::g is called a qualified name; plain g is an unqualified name.
The problem namespaces solve
Without namespaces, these two pieces of code could never live in one program, because C++ does not allow two global variables or two functions with the same signature both named g / weight:
physics library astronomy library
─────────────── ─────────────────
double g = 9.8; double g = 274.0; ← same name!
double weight(double m); double weight(double m); ← same signature!
One program, one global scope → "redefinition" errorPut each in its own namespace and the conflict disappears:
#include <iostream>
namespace physics {
double g = 9.8; // m/s^2 on Earth
double weight(double mass) { return mass * g; }
}
namespace astronomy {
double g = 274.0; // m/s^2 on the Sun's surface
double weight(double mass) { return mass * g; }
}
int main() {
std::cout << "Earth: " << physics::weight(10) << " N\n";
std::cout << "Sun: " << astronomy::weight(10) << " N\n";
std::cout << "g values: " << physics::g << ", " << astronomy::g << '\n';
}Output:
Earth: 98 N
Sun: 2740 N
g values: 9.8, 274Notice that inside physics::weight we wrote just g, not physics::g. Code inside a namespace sees the other names of that namespace directly, just as a member function sees the other members of its class.
Syntax rules
namespace name { declarations }— note there is no semicolon after the closing brace (unlike a class). Writing one is harmless (an empty declaration) but unnecessary.A namespace may be defined only at namespace scope: at global level or inside another namespace. You cannot define a namespace inside a function or a class.
A namespace is not a type. You cannot create an object of it, and it has no
public/private— everything declared in it is accessible with the qualified name.Everything not inside any namespace belongs to the global namespace, which has no name. You reach it with a leading
::, as in::value.
Namespaces Are Open: Adding Members Later
Unlike a class, which is closed at its }, a namespace can be reopened any number of times, in the same file or in different files. Each block simply adds more members. You can also declare a function inside the namespace and define it outside with a qualified name.
#include <iostream>
namespace bank {
int balance = 1000;
}
namespace bank { // reopened: adds more members
void deposit(int amount) { balance += amount; }
}
namespace bank {
void show(); // declared here ...
}
void bank::show() { // ... defined outside with a qualified name
std::cout << "Balance: " << balance << '\n'; // 'balance' found: we are inside bank
}
int main() {
bank::deposit(500);
bank::show();
}Output:
Balance: 1500This is why the standard library can spread std over dozens of headers: <iostream>, <vector> and <string> each reopen namespace std and add their own parts.
Nested Namespaces and Aliases
Namespaces can contain namespaces. Since C++17 you can write a nested namespace in one line with namespace a::b { }. Long names can be shortened with a namespace alias.
#include <iostream>
namespace company {
namespace hr {
void hire() { std::cout << "company::hr::hire\n"; }
}
}
namespace company::finance { // C++17 nested namespace definition
void pay() { std::cout << "company::finance::pay\n"; }
}
namespace cf = company::finance; // namespace alias
int main() {
company::hr::hire();
company::finance::pay();
cf::pay();
}Output:
company::hr::hire
company::finance::pay
company::finance::payYou will meet a real alias in the standard library: many programs write namespace fs = std::filesystem; (you saw std::filesystem in File Handling) and namespace rv = std::ranges::views;.
How unqualified names are looked up
When the compiler sees a plain name, it searches from the innermost scope outward and stops at the first scope that contains the name. A qualified name skips the search and goes straight to the named namespace.
#include <iostream>
int value = 1; // global namespace
namespace outer {
int value = 2;
namespace inner {
int value = 3;
void show() {
int value = 4; // local variable
std::cout << value << ' ' // 4 (local)
<< inner::value << ' ' // 3
<< outer::value << ' ' // 2
<< ::value << '\n'; // 1 (global)
}
}
}
int main() {
outer::inner::show();
}Output:
4 3 2 1 search order for an unqualified name inside show():
block scope of show() → outer::inner → outer → global (::)
value = 4 ✔ found (stop here)Using-Declarations and Using-Directives
Writing physics:: everywhere is precise but can be tiring. C++ gives two ways to bring names into the current scope, and they behave quite differently.
A using-declaration (
using ns::name;) introduces one specific name into the current scope, as if it were declared there. A using-directive (using namespace ns;) declares no names; it makes every name ofnsvisible to unqualified lookup from that scope.
#include <iostream>
#include <string>
namespace shapes {
double pi = 3.14159;
double area(double r) { return pi * r * r; }
std::string name() { return "shapes"; }
}
int main() {
using shapes::area; // using-declaration: brings ONE name
std::cout << area(2.0) << '\n';
// std::cout << pi; // error: 'pi' was not declared in this scope
{
using namespace shapes; // using-directive: ALL names become visible
std::cout << pi << ' ' << name() << '\n';
}
}Output:
12.5664
3.14159 shapesBoth obey normal scope rules: the directive inside the inner { } stops working at its closing brace.
Ambiguity: the error comes only when you use the name
Two using-directives can make the same name visible twice. That is not an error by itself — it becomes an error only when you actually use the ambiguous name unqualified:
#include <iostream>
namespace a { int x = 1; }
namespace b { int x = 2; }
using namespace a;
using namespace b; // no error yet
int main() {
std::cout << x << '\n'; // error: which x?
}e1.cpp:10:18: error: reference to ‘x’ is ambiguous
e1.cpp:4:19: note: candidates are: ‘int b::x’
e1.cpp:3:19: note: ‘int a::x’The fix is simply to qualify: a::x or b::x.
Declaration vs directive with a local variable of the same name
Because a using-declaration really declares the name in the current scope, it clashes with a local variable of the same name:
namespace a { int x = 1; }
int main() {
int x = 10;
using a::x; // error: conflicts with the local x
}e2.cpp:5:14: error: ‘int a::x’ conflicts with a previous declaration
e2.cpp:4:9: note: previous declaration ‘int x’A using-directive declares nothing; for lookup purposes the names of a behave as if they were declared in the nearest enclosing namespace (here, global). So the local variable simply hides them, silently:
#include <iostream>
namespace a { int x = 1; }
int main() {
int x = 10;
using namespace a; // fine
std::cout << x << ' ' << a::x << '\n'; // local x hides a::x
}Output:
10 1| Feature | using-declaration using ns::f; | using-directive using namespace ns; |
|---|---|---|
| Brings in | One name (all overloads of it) | Every name of the namespace, current and future |
| Is it a declaration? | Yes — acts like a declaration in this scope | No — only affects lookup |
| Same-named local in same scope | Compile error (conflict) | Local silently hides the namespace name |
| Two sources of the same name | Error at the using-declaration (for variables) | Error only when the name is used unqualified |
| Risk of surprises | Low — you list exactly what you want | High — pulls in names you never knew existed |
| Typical good use | using std::cout;, using std::swap; | Inside a function, small programs, using namespace std::literals; |
Why using namespace std; Is Considered Bad Practice
Many textbooks begin every program with using namespace std;. In a tiny program it is harmless, but understand what it does: it makes hundreds of standard names (count, distance, size, data, max, left, hash, ...) visible everywhere below it. Any of them can collide with your own names:
#include <iostream>
#include <algorithm>
using namespace std;
int count = 0; // our own global counter
int main() {
count++; // error: reference to 'count' is ambiguous
cout << count << '\n';
}e4.cpp:8:5: error: reference to ‘count’ is ambiguous
.../pstl/glue_algorithm_defs.h:102:1: note: candidates are: ‘... std::count(_ExecutionPolicy&&, _ForwardIterator, _ForwardIterator, const _Tp&)’
.../bits/stl_algo.h:4070:5: note: ‘... std::count(_IIter, _IIter, const _Tp&)’
e4.cpp:5:5: note: ‘int count’
(the same error is reported again for line 9)Our innocent variable collided with the algorithm std::count. Worse, a future version of the standard library may add new names to std, so code that compiles today may break after a compiler upgrade.
Practical rules used by most professional teams:
Never put
using namespace(any namespace) at global scope in a header file. Every file that includes your header inherits it, and they cannot undo it.In a
.cppfile it is a matter of taste; prefer qualified names or targeted using-declarations such asusing std::cout;.Small, fully self-contained programs — classroom exercises and competitive programming — commonly use
using namespace std;and that is accepted there.
Unnamed (Anonymous) Namespaces
An unnamed namespace (
namespace { ... }) gives its members internal linkage: they can be used freely in the current source file (translation unit) but are invisible to every other source file.
It is the modern C++ way to write file-private helpers, replacing the C habit of marking functions static at file scope. Let us build a small multi-file program. The header declares the public interface:
// geometry.h
#pragma once
namespace geometry {
struct Point {
double x, y;
};
double distance(Point a, Point b); // declaration only
}// geometry.cpp
#include "geometry.h"
#include <cmath>
namespace { // unnamed namespace: private to this file
double square(double v) { return v * v; }
}
namespace geometry {
double distance(Point a, Point b) {
return std::sqrt(square(a.x - b.x) + square(a.y - b.y));
}
}// main.cpp
#include "geometry.h"
#include <iostream>
namespace {
double square(double v) { return v * v * 1.0; } // a different, private square
}
int main() {
geometry::Point p{0, 0}, q{3, 4};
std::cout << "distance = " << geometry::distance(p, q) << '\n';
std::cout << "square(5) = " << square(5) << '\n';
}Compile both files together:
g++ -std=c++23 -Wall -Wextra main.cpp geometry.cpp -o app
./appOutput:
distance = 5
square(5) = 25Both files define a function square(double), yet the linker does not complain. Each unnamed namespace is unique to its file, so the two square functions are completely different entities. Without the unnamed namespaces you would get a "multiple definition of square(double)" linker error (a violation of the One Definition Rule).
| Point | Unnamed namespace | static at file scope |
|---|---|---|
| Linkage given | Internal | Internal |
| Works for functions and variables | Yes | Yes |
| Works for types (classes, enums) | Yes | No — static cannot be applied to a class definition |
| Recommended in modern C++ | Yes | Still valid, mainly in C-style code |
Never put an unnamed namespace in a header: every file that includes it would get its own private copy, which wastes space and can cause subtle bugs.
Inline Namespaces (C++11) — Library Versioning
An inline namespace is a nested namespace whose members are also treated as members of the enclosing namespace. Library authors use it to ship several versions of an API and choose a default:
#include <iostream>
namespace mylib {
namespace v1 {
void greet() { std::cout << "Hello from v1\n"; }
}
inline namespace v2 { // the current default version
void greet() { std::cout << "Hello from v2\n"; }
}
}
int main() {
mylib::greet(); // v2: members of an inline namespace act like members of mylib
mylib::v1::greet(); // old version still reachable explicitly
mylib::v2::greet();
}Output:
Hello from v2
Hello from v1
Hello from v2When version 3 arrives, the author moves the inline keyword to v3; users who wrote mylib::greet() get the new version after recompiling, while mylib::v2::greet() keeps working. The standard library uses inline namespaces for user-defined literals: std::literals::string_literals is inline inside std::literals, which is itself inline inside std. That is why using namespace std::literals; gives you the "text"s suffix. Since C++20 you can write the short form namespace mylib::inline v2 { }.
Argument-Dependent Lookup (ADL)
Here is a puzzle. In every program you write std::cout << "hi", but the operator<< that prints strings lives in namespace std, and you never wrote std::operator<<. How does the compiler find it? The answer is ADL, also called Koenig lookup.
Argument-dependent lookup: for an unqualified function call, the compiler also searches the namespaces associated with the types of the arguments (for a class type, the namespace in which the class is declared, plus those of its base classes and template arguments), in addition to normal lookup.
#include <iostream>
#include <string>
namespace school {
struct Student {
std::string name;
int marks;
};
void print(const Student& s) {
std::cout << s.name << " scored " << s.marks << '\n';
}
std::ostream& operator<<(std::ostream& os, const Student& s) {
return os << "Student(" << s.name << ", " << s.marks << ")";
}
}
int main() {
school::Student s{"Asha", 92};
print(s); // no school:: needed - found by ADL
std::cout << s << '\n'; // operator<< in school found by ADL
}Output:
Asha scored 92
Student(Asha, 92)The argument s has type school::Student, so namespace school is searched and print is found. This is exactly why you should declare operators for a class (like the operator<< from Operator Overloading) in the same namespace as the class: then they work everywhere, with no using-directive needed.
ADL applies only to unqualified function calls. Writing school::print(s) or (print)(s) turns it off, and it does nothing for variables or for arguments of built-in types like int, which belong to no namespace.
The "using std::swap" idiom
A famous use of ADL appears in generic code. We want to call a type's own optimized swap if it has one, and otherwise fall back to std::swap:
#include <iostream>
#include <utility>
namespace bigdata {
struct Matrix {
int id;
};
void swap(Matrix& a, Matrix& b) noexcept { // a cheap, custom swap
std::cout << "bigdata::swap called\n";
std::swap(a.id, b.id);
}
}
template <typename T>
void exchange(T& a, T& b) {
using std::swap; // fallback for types without their own swap
swap(a, b); // unqualified: ADL picks bigdata::swap if it exists
}
int main() {
bigdata::Matrix m1{1}, m2{2};
exchange(m1, m2);
std::cout << m1.id << ' ' << m2.id << '\n';
int x = 5, y = 7;
exchange(x, y); // ints have no namespace -> std::swap used
std::cout << x << ' ' << y << '\n';
}Output:
bigdata::swap called
2 1
7 5For Matrix, both std::swap (a template) and bigdata::swap (found by ADL) are candidates; overload resolution prefers the non-template exact match bigdata::swap. For int, ADL adds nothing, so std::swap is used. If we had written std::swap(a, b), ADL would be disabled and the custom swap would never run.
The std Namespace and using enum
Two smaller facts complete the picture:
Do not add your own declarations to namespace
std. Doing so is undefined behavior, except in the cases the standard explicitly allows — most importantly, specializing certain standard templates such asstd::hash(the hash function behind unordered_set & unordered_map) for your own type, so that it can be used as a key.C++20
using enumworks like a using-directive for the enumerators of a scoped enum (covered in Structures, Unions & Enums). It is handy inside aswitch:
#include <iostream>
enum class Color { Red, Green, Blue };
const char* toText(Color c) {
switch (c) {
using enum Color; // C++20: Red, Green, Blue usable unqualified
case Red: return "Red";
case Green: return "Green";
case Blue: return "Blue";
}
return "?";
}
int main() {
std::cout << toText(Color::Green) << '\n';
}Output:
GreenSummary of Namespace Features by Standard
| Feature | Syntax | Since |
|---|---|---|
Named namespace, reopening, :: | namespace n { } | C++98 |
| Unnamed namespace | namespace { } | C++98 (internal linkage guaranteed since C++11) |
| Namespace alias | namespace x = a::b; | C++98 |
| using-declaration / using-directive | using a::f; / using namespace a; | C++98 |
| Inline namespace | inline namespace v2 { } | C++11 |
| Nested namespace definition | namespace a::b::c { } | C++17 |
| Nested inline namespace | namespace a::inline b { } | C++20 |
using enum | using enum Color; | C++20 |
Common Mistakes
using namespace std;in a header — forces it on every includer and causes mysterious ambiguity errors.Naming your own globals
count,max,distance,datawhile usingusing namespace std;— collisions with standard names.Defining a namespace inside a function — not allowed; namespaces live only at namespace scope.
Putting
private:in a namespace — namespaces have no access control. Use an unnamed namespace or adetailsub-namespace by convention for "internal" things.Unnamed namespace in a header — each including file gets a separate copy.
Calling
std::swap(a, b)in generic code — bypasses a type's custom swap; use theusing std::swap; swap(a, b);idiom.Declaring a class's
operator<<in a different namespace from the class — then ADL cannot find it and calls fail or need extra using-declarations.Adding your own functions to
namespace std— undefined behavior (only permitted specializations are allowed).
Interview / GATE-Style Questions
Q1. What is the difference between a namespace and a class?
Both create a scope reached with ::, but a class is a type: you can create objects, it has access specifiers, and it is closed at its closing brace. A namespace is not a type, cannot be instantiated, has no access control, and can be reopened and extended across many files.
Q2. What is printed?
int x = 1; namespace n { int x = 2; void f() { int x = 3; std::cout << x << n::x << ::x; } }
321. Plain x is the local, n::x is the namespace variable, and ::x is the global one.
Q3. Two using-directives bring in a::x and b::x. Is the program ill-formed?
Only if x is used unqualified somewhere those directives are in effect. The directives themselves are fine; the ambiguity is reported at the point of use.
Q4. What is an unnamed namespace used for, and why prefer it over static?
It gives everything inside it internal linkage, so helper functions, variables and types are private to one source file and cannot clash with same-named entities in other files at link time. It is preferred because it also works for type definitions (classes, enums), which static cannot mark.
Q5. How does std::cout << s find an operator<< declared in namespace school when s is a school::Student?
By argument-dependent lookup: for an unqualified function call (including operator expressions), the namespaces associated with the argument types — here std for std::ostream and school for Student — are searched in addition to normal lookup.
Q6. Why is using namespace std; discouraged in header files?
A header is pasted into every file that includes it, so the directive leaks into all of them. They cannot remove it, and any of their names can now collide with the hundreds of names in std, including names added in future standards.
Q7. What is an inline namespace?
A nested namespace (C++11) whose members are visible as members of the enclosing namespace. It is used for API versioning: the default version is the inline one, and older versions stay accessible by their full names.
Summary
A namespace is a named scope that prevents name collisions; reach its members with
ns::name, and the global namespace with::name.Namespaces are open: they can be reopened in many places and files; they can be nested (
a::b::cin one line since C++17) and aliased.using-declaration brings in one name and acts as a declaration; using-directive makes all names visible to lookup, with ambiguity errors appearing only at use.
Avoid
using namespace std;in headers and in large programs; prefer qualified names or targeted using-declarations.Unnamed namespaces give internal linkage — the modern replacement for file-level
static.Inline namespaces support versioning; the standard literals use them.
ADL searches the namespaces of argument types for unqualified calls, which is why operators should live next to their class and why the
using std::swap;idiom works.