Suneeldatta Kolipakula
Suneeldatta Kolipakula

Reputation: 217

why we cannot print the value of enum class as enum in c++

Getting error while trying to print the enum class object. I am getting the error while trying to print this. where am I doing mistake?

#include <iostream>

using namespace std;

int main()
{

enum weekdays{sunday,monday,tuesday};
cout<<monday<<endl; // getting value as 1 as i expected.


enum class Weekday{sunday,monday,tuesday};
enum class Holiday{sunday,saturday};

Weekday wday=Weekday::monday; 

cout<<Weekday::monday<<endl; // getting error
cout<<wday<<endl; //getting error
return 0;
}

Upvotes: 0

Views: 1491

Answers (2)

Tony Delroy
Tony Delroy

Reputation: 106076

As enum class has stronger type safety than enum, you'll need to explicitly request a conversion to the underlying integral value:

#include <type_traits>
...
std::cout << static_cast<std::underlying_type_t<Weekday>>(Weekday::monday) << '\n';

Upvotes: 1

eerorika
eerorika

Reputation: 238311

why we cannot print the value of enum class as enum in c++

Because enum classes are different from enums. One of the differences is that unlike enum, enum class instance does not implicitly convert to the underlying integer type. Since you didn't define an output stream insertion operator for your enum class, you cannot insert it into an output stream.

where am I doing mistake?

The mistake is assuming that enum classes behave the same as enums.

If i want to know the value that is being stored in Weekday wday=Weekday::monday; how can i know it.??

By converting it explicitly. You can use a static cast.

Upvotes: 5

Related Questions