capypad
0 day streak
cpp / beginner
Snippet

The Scope Resolution Operator

The :: operator accesses items from specific scopes. Use namespace::item to reach a namespaced variable, or ::variable to access the global scope. This allows precise control over which variable you intend to use when names might conflict.

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>
 
int value = 100;
 
namespace Outer {
int value = 200;
namespace Inner {
int value = 300;
void print() {
std::cout << "Inner: " << value << std::endl;
std::cout << "Outer: " << Outer::value << std::endl;
std::cout << "Global: " << ::value << std::endl;
}
}
}
 
int main() {
Outer::Inner::print();
std::cout << "Direct Outer: " << Outer::value << std::endl;
std::cout << "Direct Global: " << ::value << std::endl;
return 0;
}
Breakdown
1
::value
The leading :: accesses the global scope variable
2
Outer::value
Accesses 'value' inside the Outer namespace
3
Outer::Inner::print()
Navigates through nested namespaces to call a function
4
std::cout << "Inner: " << value
Inside Inner, unqualified 'value' refers to Inner::value