Back to results for “Namespaces”
C++ › Namespaces

What is a namespace and why use one?

Beginner

Answer

A namespace is a named scope that groups related declarations (functions, classes, variables) to prevent name collisions between different libraries or modules. Qualifying names with the namespace (ns::name) disambiguates them. Namespaces are essential for organizing large codebases and avoiding clashes with third-party or standard-library names.
namespace math {
    int add(int a, int b) { return a + b; }
}
int r = math::add(2, 3);
Real-world example Two libraries each define a Logger class; putting them in namespaces avoids the collision.

Common follow-ups: How do namespaces prevent collisions? | How do you access a name in a namespace?