0 day streak
cpp / intermediate
Snippet

Strongly Typed Scoped Enumerations

Scoped enumerations (enum class) prevent name collisions by requiring the enum name as a prefix. Unlike traditional enums, they do not implicitly convert to integers, which enforces type safety and prevents accidental mathematical operations on symbolic constants.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
enum class SecurityLevel {
Low,
Medium,
High
};
int main() {
SecurityLevel current = SecurityLevel::Medium;
// Comparison requires explicit scope
if (current == SecurityLevel::Medium) {
std::cout << "Level is balanced." << std::endl;
}
// Error: int x = current; // No implicit conversion to int
return 0;
}
Breakdown
1
enum class SecurityLevel
Declares a scoped enumeration that creates its own namespace for its values.
2
SecurityLevel::Medium
Accesses the enum value using the scope resolution operator.