Namespace Fundamentals
What is a Namespace?
In C++, a namespace is a declarative region that provides a scope for identifiers such as names of types, functions, variables, and other declarations. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.
Basic Namespace Syntax
namespace MyNamespace {
// Declarations and definitions go here
int myVariable = 10;
void myFunction() {
// Function implementation
}
}
Accessing Namespace Members
Scope Resolution Operator (::)
int main() {
// Accessing namespace members explicitly
int value = MyNamespace::myVariable;
MyNamespace::myFunction();
return 0;
}
Nested Namespaces
namespace OuterNamespace {
namespace InnerNamespace {
int nestedVariable = 20;
}
}
// Accessing nested namespace
int value = OuterNamespace::InnerNamespace::nestedVariable;
Namespace Characteristics
Feature |
Description |
Scope Isolation |
Prevents naming conflicts |
Code Organization |
Groups related declarations |
Modularity |
Improves code structure |
Common Namespace Patterns
graph TD
A[Global Namespace] --> B[Standard Library Namespace std::]
A --> C[Custom Namespaces]
C --> D[Project-Specific Namespaces]
C --> E[Library Namespaces]
Standard Library Namespace
Most C++ standard library components are defined in the std::
namespace:
#include <iostream>
int main() {
// Using standard library with namespace
std::cout << "Hello from LabEx C++ Tutorial!" << std::endl;
return 0;
}
Key Takeaways
- Namespaces provide a way to group related code
- They help prevent naming conflicts
- Can be nested and explicitly accessed
- Standard library uses
std::
namespace
- Improves code organization and readability