enum Vs enum class in C ++
In C++, enumerations (enums) are a powerful tool for creating named sets of integer constants. They help improve code readability and maintainability by providing meaningful names to numeric values. However, C++ offers two ways to define enums: the traditional enum and the more modern enum class. In this blog, we’ll explore the differences between these two options and when to use each with the help of examples.
This post was originally posted at https://agrawalsuneet.github.io/blogs/enum-vs-enum-class-in-c++/ and later reposted on Medium.
Traditional enum
The traditional enum in C++ allows you to define a set of named integer constants without restricting their underlying type. This means the values are not encapsulated within a specific scope, leading to potential namespace clashes.
#include <iostream>
enum Color {
Red,
Green,
Blue
};
int main() {
Color myColor = Red;
// ...
return 0;
}
In the example above, Red, Green, and Blue are in the same scope as the surrounding code, which can lead to naming conflicts if similar names exist elsewhere in your program.
enum class
In contrast, C++11 introduced the enum class (also known as a scoped enumeration or strong enum) to address the issues of traditional enums. enum class provides stronger type safety by encapsulating the values within their own scope. This makes it less error-prone and more self-contained.
#include <iostream>
enum class Color {
Red,
Green,
Blue
};
int main() {
Color myColor = Color::Red;
// ...
return 0;
}
In this version, Color::Red, Color::Green, and Color::Blue are scoped within the Color enum class, reducing the chances of naming conflicts.
Differences Between enum and enum class
While both traditional enum and enum class serve the purpose of defining named sets of integer constants, they differ in several important ways.