Quasar
Quasar

Reputation: 295

enum class: syntax details: types and generalities

What does the following C++11 code mean?

    enum class myclass_t : int 
    {
       one_element= 1, second_element = 2
    };

First: why is there the int? It obviously refers to the type of 1 and 2 but do we need it and if so why? Second: what is the difference between a normal class an enum class and a normal enum. I have looked it up but don't really get it Thanks.

Upvotes: 0

Views: 69

Answers (1)

Justin Randall
Justin Randall

Reputation: 2278

Why is there the int? It obviously refers to the type of 1 and 2 but do we need it and if so why?

You don't need to do it, but in C++11 now that you can specify the underlying type you can get the benefits of type safety. Instead of the compiler changing the underlying type, it will warn you if you have an expression that is out of range for that type. Imagine if it were something like the following.

enum class myclass_t : short 
{
   first_element = 1,
   second_element = 2,
   third_element = 65536
};

Now when you try to compile this code, your compiler will give you a friendly reminder that you've exceeded the valid range.

error: enumerator value 65536 is outside the range of underlying type 'short int'
third_element = 65536
                ^

Admittedly there is not much value in scoping your enum class to int since it is that type by default, but it is largely considered good practice to implement type safety when it's available to you. Catching mistakes early is always a good thing.

What is the difference between a normal class an enum class and a normal enum?

This question is answered here.

Upvotes: 1

Related Questions