Lesson 165 +10 XP

Namespaces

Namespaces

When two parts of a program want to use the same name, they collide. A namespace is a named container that keeps sets of names apart.

A simple namespace

Use namespace to group names:

namespace my {
    int x = 5;
    int add(int a, int b) { return a + b; }
}

Here my is a namespace holding a variable and a function. To reach a name inside, use the scope resolution operator :::

cout << my::x;           // the x inside namespace my
int total = my::add(2, 3);  // the add inside namespace my

The std namespace

The C++ standard library keeps almost everything inside the namespace std. That's why you write:

std::cout << "Hello";
std::cin >> value;

cout is not a global name - it lives in std. Writing cout without qualification fails unless you add using namespace std; first.

Avoiding name collisions

Two libraries that both define print would clash. Wrapping each in its own namespace solves it cleanly:

namespace alice {
    void print() { cout << "Alice"; }
}

namespace bob {
    void print() { cout << "Bob"; }
}

alice::print();   // prints Alice
bob::print();     // prints Bob

The same name, two namespaces, zero confusion.

When to use namespaces

  • For library and API code: it protects your names from clashing with user code.
  • For large programs: grouping related functions keeps things organized.
  • For small one-file programs, a single namespace may be overkill - but getting in the habit never hurts.

TL;DR

  • A namespace is a named group of declarations.
  • namespace my { int x; } defines one; use my::x to reach the name.
  • std is the namespace holding the C++ standard library (std::cout).
  • Namespaces prevent name collisions between different code.
  • Use them for libraries and big projects; they keep names organized.