TITLE: enum initializer, assignment, and conversions (Newsgroups: comp.lang.c++.moderated, 11 Jun 98) [ This is a discussion about enum and int conversions in the code enum testenum { zero = 0, one = 1, ... }; - adc ] ELTSCHKA: Christopher Eltschka >> While there's an implicit cast from enum to int, there's no implicit >> cast from int to enum. So two+1 is legal, but implicit conversion >> to testenum is prohibited. However you are allowed to explicitly >> cast the value to testenum: ELEVELD: D.J.Eleveld@anest.azg.nl >First of all, thanks to everyone who gave me sucha clear answer to my >orinigal post. However, I'm confused about casting here. I'm told that >there is no implicit conversion between an enum and an int, however int >the definition of the enum that I showed it really looks like there is > an implicit cast going on. The line: > >enum testenum { zero = 0, <--- this looks like an implicit conversion to me > ...... > >Are implicit conversion allowed in definitions, but not anywhere else? CLAMAGE: clamage@Eng.Sun.COM (Steve Clamage), There is a special rule for enum type definitions. The initializer must be a constant-expression of integral or enum type. Its value is used as the value of the enumerator. In your example, the int value 0 is used for the value of the enumerator "zero". ELEVELD: >Similarly with : > >enum testenum { zero = 0, > one, > one_or_zero = zero | one, > ..... > }; >Is this legal code? CLAMAGE: Yes. An enum is promoted to an integer type in any expression, so "zero|one" becomes "0|1", which is a constant integer expression, and so can be used to initialize one_or_zero. ELEVELD: >What if I have a special operator for or'ing the enums ... CLAMAGE: Such a function could not be declared until after the enum definition, so it can't be used in the enum definition. If you could somehow find a way to reference such a function, a constant-expression cannot include a function call, so such an initializer would not be valid. You could declare the function and use it later to initialize new constant of type testenum. Example: testenum operator|(testenum a, testenum b) { return testenum(a|b); } testenum c, d; ... const testenum x = c|d; // OK: operator| returns a testenum const testenum y = 0|1; // ERROR: using int to initialize testenum TRIBBLE: David R Tribble About the last initialization of 'y': could I define an assignment operator that does the conversion for me, as in: const testenum & operator =(testenum &d, int v) { d = static_cast(v); return d; } const testenum z = 0|1; // Does this work? const testenum w = 1|c; // If so, this should too