Namespaces
1 min read
Namespaces
Namespaces prevent name collisions by grouping related names under a common prefix. The standard library lives in std; your own code should live in its own namespace.
Declaring a namespace
#include <iostream>
namespace geometry {
double area(double radius) {
return 3.14159 * radius * radius;
}
struct Point {
double x, y;
};
}
int main() {
double a = geometry::area(5.0);
std::cout << a << "\n";
geometry::Point p = {1.0, 2.0};
std::cout << p.x << " " << p.y << "\n";
}
:: is the scope resolution operator. geometry::area means "the function area inside the geometry namespace."
using declarations
A using declaration brings one specific name into scope:
using geometry::area;
int main() {
std::cout << area(3.0) << "\n"; // no geometry:: prefix needed
}
using namespace
using namespace std; brings every name from std into scope. It is convenient in short programs but dangerous in headers and large codebases — it defeats the purpose of namespacing by re-introducing collision risk:
// Fine in a .cpp file, never in a header
using namespace std;
cout << "Hello\n";
Prefer explicit prefixes (std::cout) or targeted using declarations.
Namespace aliases
Long nested namespace names can be shortened:
namespace fs = std::filesystem;
fs::path p = "/tmp/file.txt";
if (fs::exists(p)) { /* ... */ }
Nested namespaces
Namespaces can be nested. C++17 added a compact syntax:
// Old style
namespace app {
namespace network {
namespace http {
void get() {}
}
}
}
// C++17 compact style
namespace app::network::http {
void get() {}
}
app::network::http::get();
Anonymous namespaces
An anonymous namespace makes names visible only within the current translation unit (.cpp file). It is the C++ replacement for C's static at file scope:
namespace {
int helper_counter = 0; // not visible outside this .cpp file
void helper() {
helper_counter++;
}
}
Use anonymous namespaces for implementation details you do not want to expose, instead of polluting the global namespace.
inline namespaces (versioning)
inline namespace makes the contents of the nested namespace directly accessible through the outer one. Commonly used for library versioning:
namespace mylib {
inline namespace v2 {
void run() { /* ... */ }
}
namespace v1 {
void run() { /* ... */ }
}
}
mylib::run(); // calls v2::run — the inline version
mylib::v1::run(); // calls v1::run explicitly
Learn modern C++ through working code. Each chapter introduces one concept — variables, functions, classes, templates, smart pointers, concurrency — with a clear example, a line-by-line explanation, and notes on how it applies in real programs.
View book →