BoSsYyY
BoSsYyY

Reputation: 563

How is the implicit cast from enum type to int possible?

#include "stdafx.h"
#include<iostream>
#include<typeinfo>

using namespace std;

enum dayOfWeek : short { M = 10, TU, W, TH, F, SA, SU };

int main()
{
    dayOfWeek d = TU;
    int u = d; // HOW ???
    return 0;
}

Now could anybody explain to me how this happens? How did this implicit cast work?

Upvotes: 0

Views: 4433

Answers (2)

Cory Kramer
Cory Kramer

Reputation: 117876

As noted in the documentation for enum the values are implicitly convertible to integral types

Values of unscoped enumeration type are implicitly-convertible to integral types. If the underlying type is not fixed, the value is convertible to the first type from the following list able to hold their entire value range: int, unsigned int, long, unsigned long, long long, or unsigned long long. If the underlying type is fixed, the values can be converted to their promoted underlying type.

If you want to disallow this implicit conversion you can use an enum class

enum class dayOfWeek : short { M = 10, TU, W, TH, F, SA, SU };

int main()
{
    dayOfWeek d = dayOfWeek::TU;
    int u = static_cast<int>(d);
    return 0;
}

Upvotes: 1

WhiZTiM
WhiZTiM

Reputation: 21576

There is no explicit cast there. You explicitly made (C++11 and above) the underlying type of your enum a short; which is implicitly convertible to int in your assignment.

However, whether you have an explicit underlying type, or not, the C++ standard explicitly states that the values of unscoped enums are implicitly convertible to integral types.

This is not the case with enum class which is a better alternative.

Upvotes: 3

Related Questions