Skip to content

Module 7 · Templates, Exceptions, Namespaces and Files — topic 3 of 4

Namespaces

Namespaces prevent name clashes between libraries and modules. Learn declaring namespaces, the :: operator, using-declarations, nested and unnamed namespaces, and aliases.

Beginner 11 min read·Lesson 29 of 40 in C++ Programming

Learning objectives

  • Declare and use namespaces
  • Choose between qualified names, using-declarations and using-directives
  • Use unnamed namespaces for internal linkage

Definition

A namespace is a named declarative region that groups identifiers to avoid name collisions; names inside are referred to with the scope-resolution operator ::.

Introduction

Two libraries might both define a function called log or a class called Vector. Namespaces keep them apart: math::Vector and gfx::Vector can coexist.

C had only one global namespace, so libraries prefixed every name (SDL_Init, png_read). Namespaces give the same protection with less noise, and they can be nested and aliased to match a project's structure.

Why it matters

Every standard library name is in std; understanding namespaces explains why.

Large projects organise code into namespaces per module or company.

Detailed explanation

namespace kenholt { int version() { return 1; } } — call it as kenholt::version().

A namespace can be reopened in several files; its contents accumulate.

using std::cout; (using-declaration) imports one name; using namespace std; (using-directive) imports everything and risks clashes — never put it in a header.

C++17 nested syntax: namespace company::project { ... }. Aliases shorten long names: namespace fs = std::filesystem;.

An unnamed namespace in a .cpp file makes its contents visible only in that file — the modern replacement for file-level static.

Syntax

C++
namespace geometry {
double area(double r) { return 3.14159 * r * r; }
}
namespace finance::tax {
double gst(double amount) { return amount * 0.18; }
}
namespace {
int helper() { return 42; } // private to this file
}
namespace ft = finance::tax;
  • ::name refers to the global namespace.
  • Prefer qualified names in headers.
  • Unnamed namespaces replace static helper functions.

Code examples

Avoiding a clash

C++
#include <iostream>
namespace metric { double distance(double km) { return km; } }
namespace imperial { double distance(double km) { return km * 0.621371; } }
int main() {
std::cout << metric::distance(10) << " km = " << imperial::distance(10) << " mi\n";
return 0;
}
Output
10 km = 6.21371 mi

using-declarations and aliases

C++
#include <iostream>
namespace kenholt::skills::util {
int square(int x) { return x * x; }
}
int main() {
namespace ku = kenholt::skills::util;
using std::cout;
cout << ku::square(12) << '\n';
return 0;
}
Output
144

More examples

Organising a small library

C++
#include <iostream>
#include <string>
namespace bank {
namespace detail { // implementation details
bool valid_amount(double a) { return a > 0 && a < 1e7; }
}
class Account {
public:
bool deposit(double a) {
if (!detail::valid_amount(a)) return false;
balance_ += a;
return true;
}
double balance() const { return balance_; }
private:
double balance_ = 0;
};
std::string version() { return "1.2"; }
}
namespace {
void report(const bank::Account& a) { std::cout << "balance: " << a.balance() << '\n'; }
}
int main() {
bank::Account acc;
acc.deposit(2500);
acc.deposit(-10);
report(acc);
std::cout << "bank library v" << bank::version() << '\n';
return 0;
}
Output
balance: 2500
bank library v1.2

Step-by-step explanation

  • bank::detail signals internal helpers not meant for users.
  • Inside bank, detail::valid_amount can be named without the outer prefix.
  • The unnamed namespace makes report private to this file.
  • Users refer to bank::Account explicitly.

Expected output

Running “Organising a small library” prints exactly:

TextOutput
balance: 2500
bank library v1.2

Practical applications

  • Boost puts everything in boost::.
  • Google's style guide requires project namespaces.
  • Libraries hide internals in detail namespaces.

Best practices

  • Wrap project code in a namespace.
  • Use unnamed namespaces for file-private helpers.
  • Qualify names in headers; use using-declarations only in .cpp files and small scopes.

Common mistakes

using namespace std in a header

Avoid

// header.hpp
using namespace std;

Prefer

// header.hpp
std::string name();

It affects every file that includes the header and can cause hard-to-find clashes.

Ambiguity from two using-directives

Avoid

using namespace metric;
using namespace imperial;
distance(5);

Prefer

metric::distance(5);

Both namespaces provide distance, so the unqualified call is ambiguous.

Important notes

  • Argument-dependent lookup (ADL) finds functions in the namespace of their arguments; that's why std::cout << s finds std::operator<< without qualification.
  • Inline namespaces are used for library versioning.

Key takeaways

  • Namespaces group names to avoid clashes.
  • Access with ns::name; alias long names.
  • Unnamed namespaces give internal linkage.

Try it yourself

  1. 1
    Put two functions with the same name in different namespaces and call both.
  2. 2
    Move a project's helper functions into an unnamed namespace.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

5 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhy should `using namespace std;` never appear in a header file?
  • BeginnerWhat does an unnamed namespace (`namespace { ... }`) in a .cpp file do?
Practise this topic