C++ Namespaces
A namespace groups related names (functions, classes, variables) under a common prefix to avoid naming collisions, e.g. the standard library lives inside `namespace std`. You define one with `namespace name { ... }` and access members with `name::member`.
`using namespace std;` imports all names from std into the current scope, which is convenient for small programs but can cause naming clashes in larger projects, so many style guides avoid it in header files.
Defining a namespace
`namespace math { int square(int x) { return x*x; } }` groups square() under the math namespace; call it as `math::square(4)`.
using namespace and using declarations
`using namespace std;` imports everything from std. A safer alternative is `using std::cout;`, which imports only the specific name you need.
namespace math {
int square(int x) { return x * x; }
}
int main() {
std::cout << math::square(4);
}16The function is called with the math:: prefix to specify its namespace.
Key points
- namespace groups names to avoid collisions.
- Access members with namespace::member.
- using namespace std imports all std names into scope.
- Avoid using namespace std in header files to prevent clashes.
