As a little project for myself to prove myself in the C++ world, I've decided to get a little text-based game going. I had the following:
enum monsterType {Zombie,Skeleton,Orc};
And later, in a class with a private monsterType Kind, a constructor that contained
Kind = rand() % 3;
It's getting mad at me for monsterType not being compatible with int. But I thought enums were pretty much ints? Casting it to monsterType helped, but I'm still confused.
In your example Zombie will have value 0, Skeleton value 1 and Orc value 2.
The enums can be converted to int implicitly because that conversion is always safe.
If you try to convert an int to the enum type that will not always generate a valid enum value.
Example: If this was allowed monsterType Kind = 4;
then Kind will not equal any of Zombie, Skeleton and Orc. This is often what you want to avoid. You want the enum variable to be one of the values you have specified as valid!
If you really don't want this behavior just use int (make Kind an int) everywhere. You could also use a cast Kind = static_cast<monsterType>(rand() % 3); but then you should really make sure that the value is a valid enum value.
Since enumerations are distinct
types, objects of type color can be assigned only values of type color.
color c = 1; // error: type mismatch,
// no conversion from int to color
int i = yellow; // OK: yellow converted to integral value 1
// integral promotion
Note that this implicit enum to int conversion is not provided for a scoped enumeration
There is a difference between C and C++ Standards. In C enumerations have integral type.