Table of Contents
Scoped enumerations were introduced in C++11 to provide a safer and more strongly typed alternative to traditional enumerations. Unlike regular enumerations, the enumerator names are scoped within the enumeration and do not implicitly convert to integers.
Using scoped enumerations helps prevent name conflicts and improves type safety, making them the preferred choice in modern C++ programs.
Source Code #
#include <iostream>
enum class Day
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
};
int main()
{
Day today = Day::Wednesday;
std::cout << "Underlying value: "
<< static_cast<int>(today) << '\n';
return 0;
}
Output #
Underlying value: 3
Explanation #
- The
enum classkeyword defines a scoped enumeration. - Enumerator names belong to the scope of the enumeration and must be accessed using the scope resolution operator (
::). Day::Wednesdayrefers to theWednesdayenumerator of theDayenumeration.- Scoped enumerations do not implicitly convert to integer types.
static_cast<int>(today)explicitly converts the enumeration value to its underlying integer type for display.- Scoped enumerations prevent naming conflicts that can occur with traditional enumerations.
- They provide stronger type safety by preventing unintended conversions between integers and enumeration values.
return 0;terminates the program successfully.