What is the difference between the enum and enum class?

Michał Balicki Avatar by Michał Balicki
on July 13, 2022

Hello

In today's post, I'd like to start a series on recruitment questions for C++ developers. The first question I would like to answer is "What is the difference between the enum and enum class?". When answering such a question we should consider two things:

First, let me explain the issue of casting. In fact, this is the main difference between "old-style" enum and enum class. For the "old-style" enum, no explicit conversion is needed. It's not necessary to use static_cast or cast from C language to display the number correlated with enum value. This is shown in the example below:

We can see that the value 1 is displayed for BLUE without casting to int. As for the enum class, we need to do an explicit cast using static_cast. Example below:

Another issue is the potential name conflict that can occur when we are using "old-style" enum. This is illustrated by the example below:

In this case, it is detected by the compiler, but I've heard it may have been ignored by the compiler in the past. This could cause some ambiguity, e.g. in IF statements in which we use a duplicate enum. The use of an enum class solves these types of problems. Below is an example:

As we can see, here, the need to use an additional scope resolution operator protects against a name conflict.

To sum up, when we get such a question during a job interview, we can answer in the following way:

“THE DIFFERENCE CONCERNS MAINLY TWO ISSUES. THE FIRST POINT IS ABOUT CASTING. IN THE CASE OF THE "OLD-STYLE" ENUM, WE CAST IT TO AN INT VIA IMPLICIT CONVERSION. IN THE CASE OF ENUM CLASS, WE NEED TO EXPLICITLY CONVERT USING STATIC_CAST. ANOTHER ISSUE IS THE NAME CONFLICT THAT CAN OCCUR WHEN WE ARE USING "OLD-STYLE" ENUM. ENUM CLASS SOLVES THIS PROBLEM BEACUSE IT'S STRONGLY TYPED. IN THE CASE OF IT'S USE, IN ADDITION TO REFERRING TO AN SPECIFIC VALUE, WE MUST ALSO INDICATE WHICH ENUM CLASS WE MEAN USING SCOPE RESOLUTION OPERATOR.”

You Might Want To Read...
Fishing Fishing summary for 2023 and plans for 2024

House Building a house - the next stage of work

General How is it going?