C++ Namespaces
π¦ C++ Namespaces
A namespace in C++ is used to organize code and avoid name conflicts, especially in large programs or when using multiple libraries.
πΉ 1. Why Use Namespaces?
Prevent name clashes
Organize large codebases
Improve readability and maintenance
Avoid global scope pollution
Example problem:
What if two libraries define count?
β‘ Namespace solves this.
πΉ 2. Basic Namespace Syntax
Access members:
πΉ 3. Using using Keyword
Using Specific Members (Recommended)
Using Entire Namespace β (Not Recommended)
β Convenient for small programs
β Risky in large projects
πΉ 4. Standard Namespace (std)
Most C++ library features are inside std.
πΉ 5. Nested Namespaces
Access:
C++17 Shortcut
πΉ 6. Anonymous Namespace
Used for file-level scope (internal linkage).
β Accessible only in that file
β Alternative to static
πΉ 7. Namespace Aliasing
Shorten long namespace names.
πΉ 8. Extending a Namespace
Namespaces can be split across multiple files.
πΉ 9. Namespace vs Class
| Namespace | Class |
|---|---|
| Organizes code | Models objects |
| No access specifiers | Has access control |
| No instances | Objects created |
| Cannot be instantiated | Can be instantiated |
β Common Mistakes
Never add to std namespace.
π Summary
Namespace avoids name conflicts
Use
::scope resolution operatorstdis the standard namespacePrefer specific
usingdeclarationsAnonymous namespaces limit file scope
