Advertisement
Beginner C++, Namespaces

What is a namespace and why use one?

Short 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.

Save C++ mock interview
Advertisement
AModel 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.
Likely follow-ups
  • How do namespaces prevent collisions? | How do you access a name in a namespace?
Related topics