Enumeration Issue/learning point

I see that with enumerated code often times will see this:

enum Animal
,
,
,
;

then later in code:

Animal animal;
cout<<animal;
my question is abt Animal animal

it looks so close to Class class
class.foo (without creating this object)

any relationship?
Last edited on
Both Animal and Class are types. When creating a variable you put the name of the type first, followed by the name of the variable. This is no different than how you create variables of simple types like int and double.

TypeName variableName;
Seems there are a few ways to manipulate type enum variables

enum Ship
{
SHIP_BATTLESHIP,
SHIP_AIRCRAFT_CARRIER,
SHIP_CARGO_SHIP,
SHIP_DESTROYER,
SHIP_BARGE,
SHIP_TUGBOAT,
};

(there is a question below)

can do:
Ship ship = SHIP_BATTLESHIP;
cout<<ship<<endl;
int ship_1 = SHIP_CARGO_SHIP;
cout<<ship_1;

Ship ship = 5 // compiler error ?mixing types? type Ship var ship = int

You can type cast (in this example)
Ship ship = static cast <Ship>(5);

I understand the static cast. What I don't understand is what is "5" that's being type casted
in my list above. I should know, I wrote it, but I am using another source as well.
Last edited on
If you don't specify what integer value that the enumerators should have, the first one gets value 0 and the next ones get one plus the previous value. This means SHIP_BATTLESHIP is 0, SHIP_AIRCRAFT_CARRIER is 1, and so on.

Assigning an integer to an enumeration object is not safe because there are many integer values that does not correspond to a valid enumerator. That's one reason why it's not allowed.

When you use the cast you (the programmer) are responsible that the conversion from integer to enumerator is safe. In this case you know that 5 corresponds to SHIP_TUGBOAT so there is no problem, but if you tried to cast an integer that is not 0-5, you do have a problem.
Last edited on
This kind of cast is very dangerous. '5' changes its meaning if you change the enum.
I understand. Thx for replying.
Just for a second we humor that ugly static cast. What is the programmer trying to do with casting a static to (5)? What does it correspond to? SHIP_TUGBOAT corresponds to 5 already.
The difference between SHIP_TUGBOAT and 5 is the types. SHIP_TUGBOAT has type Ship while 5 has type int. The conversion from Ship to int is implicit. The conversion from int to Ship has to be done explicit (using a cast).

There is a new type of enum called scoped enumeration. One of its features is that it doesn't do implicit conversions at all.

http://www.stroustrup.com/C++11FAQ.html#enum
Last edited on
Got it, finally. Thx!
Topic archived. No new replies allowed.