Skip to content
Codescope

Namespaces

Scoping names, and why `using namespace std` belongs in no header.

intro7 min6 steps

Before you start

As a program grows, name collisions become inevitable. Two libraries both want to call something sort or Result or log. **Namespaces** are C++'s answer: a way to say "my sort" versus "their sort" without either changing.

A namespace is just a labelled scope. std::cout means "cout inside the std namespace". The :: is the scope resolution operator — it drills into the namespace to find the name.

This lesson shows the three ways to reach a namespaced name — fully qualified, one-name imports, and blanket imports — and why the blanket version (using namespace std) is fine in a .cpp file but a landmine in a header.

math::

math::
add()
 
pi
 

physics::

physics::
pi
 
gravity
 

Two pi variables, zero conflict. The namespace is part of the name.

Step 1 of 6. Two namespaces, same name. Both `math` and `physics` define a variable called `pi`. Without namespaces, this would be a linker error — two global symbols with the same name. Namespaces are compile-time scopes. They add a prefix to every name inside them, so the linker sees `math::pi` and `physics::pi` as different symbols.

01 / 06

Step 01 / 06

Two namespaces, same name

Both math and physics define a variable called pi. Without namespaces, this would be a linker error — two global symbols with the same name.

Namespaces are compile-time scopes. They add a prefix to every name inside them, so the linker sees math::pi and physics::pi as different symbols.

namespaces.cppC++
#include <iostream>namespace math {    int add(int a, int b) { return a + b; }    double pi = 3.14159;}namespace physics {    double pi = 3.14159265;    double gravity = 9.81;}// Qualified access — always worksint r1 = math::add(2, 3);double r2 = physics::gravity;// using-declaration — one nameusing math::add;int r3 = add(4, 5);            // math::add// using-directive — all namesusing namespace math;double r4 = pi;                 // math::pi// Which pi? ambiguous if physics is also brought in// using namespace physics;     // error: 'pi' is ambiguous