In my class I defined an enum like this:
class myClass
{
public:
enum access {
forL,
forM,
forA
};
typedef access AccessType;
AccessType aType;
};
Later in defined an object like this:
myClass ob;
ob->aType = 0;
However I get this error:
error: invalid conversion from 'int' to 'myClass::AccessType {aka myClass::access}' [-fpermissive]
Don't enum fields map to integers?
You can't do an implicit cast from int -> enum, since at compile time there is no way to know that the cast is valid.
You can do implicit casts the other way, so you could (if you wanted to) do:
No, they are stored as integers but they are distinct types (e.g. you can even overload based on the enum type). You must convert explicitly:
or ever better write the corresponding named value of the enum:
Or perhaps if you want to use the enum just as a set of integer constants, change the type of the field:
Conversion from enum to int is implicit.
Enumeration members are backed by integer values but there is no implicit conversion from an integer to an enum type. You need to use an explicit cast if you really want to write it like this:
I just had same issue. i have to initialize an object from what i read in an xml file and for sure, i have no control over what could happen to that file.
Constructor has an enum as argument :
So when parsing the Xml i have to cast it. I prefered then to handle the cast in the constructor so the other classes do not have to know which is the valid enums.
But no way to be sure the value coming from xml will be in the correct range.
Here is the solution i came with :
This is an implementation choice, to force a default value in case of non consistent data. One could prefer throwing out an exception, in my case it will do this way.