capypad
0 day streak
cpp / beginner
Snippet

Introduction to Namespaces

A namespace is a named scope that groups related code elements together, preventing naming conflicts. In larger projects, two different parts might define a function with the same name; namespaces solve this by qualifying the name with the namespace prefix.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
 
namespace Math {
const double PI = 3.14159;
double square(double x) {
return x * x;
}
}
 
namespace Text {
void greet() {
std::cout << "Hello from Text namespace!" << std::endl;
}
}
 
int main() {
std::cout << "Pi: " << Math::PI << std::endl;
std::cout << "5 squared: " << Math::square(5) << std::endl;
Text::greet();
using namespace Math;
std::cout << "Using namespace: " << square(3) << std::endl;
return 0;
}
Breakdown
1
namespace Math {
Declares a namespace called 'Math' to group math-related code
2
const double PI = 3.14159;
A constant stored inside the Math namespace
3
namespace Text {
A separate namespace for text-related functions
4
Math::square(5)
The :: operator accesses square from the Math namespace
5
using namespace Math;
All members of Math become directly accessible without ::