capypad
0 day streak
cpp / beginner
Snippet

Understanding Namespaces

Namespaces organize code into named scopes, preventing name conflicts. The std namespace contains cout and other standard library items. Here we create two custom namespaces (school and sports) that both define a studentCount variable without conflict. Use the scope resolution operator (::) to access namespace members, or 'using namespace' to bring all members into the current scope.

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
27
#include <iostream>
 
namespace school {
int studentCount = 25;
void printInfo() {
std::cout << "School has " << studentCount << " students" << std::endl;
}
}
 
namespace sports {
int studentCount = 15;
void printInfo() {
std::cout << "Sports club has " << studentCount << " members" << std::endl;
}
}
 
int main() {
school::printInfo();
sports::printInfo();
using namespace school;
std::cout << "Direct access: " << studentCount << std::endl;
return 0;
}
Breakdown
1
namespace school {
Begins a namespace block named 'school' to group related code
2
int studentCount = 25;
Variable inside the school namespace
3
school::printInfo();
Calls printInfo from school namespace using scope resolution operator
4
sports::printInfo();
Calls printInfo from sports namespace - same function name, different namespace
5
using namespace school;
Brings all school namespace members into current scope for direct access