A quick question around enumerations

Hi,

Let's say I have a "Weapon" class, which stores the weapon "Type" as an enumeration.
As I instantiate this class I wish to specify what type of weapon this is, my options are {Axe, Dagger, Sword, Mace}. Is there any way to 'lock' a specific value to represent the class?

A simpler way to do this would be to use an integer and a validation method that assigns '0' == "Sword", which is close to what I've actually done - I'm just curious...

Is it possible for an enumeration to operate like this?

Thanks!
I don't know what you mean by "lock", but I think you mean you want each member of Weapon to have a constant value.

Assuming that is indeed what you mean,
The long answer:
Read http://msdn.microsoft.com/en-us/library/vstudio/2dzy4k6e.aspx
This will tell you everything you're asking about.

The short answer: yes. By default, enum Weapon { Axe, Dagger, Sword, Mace } will create the enum where Axe has value 0, Dagger has value 1, Sword has value 2, and Mace has value 3.
Suppose you want to decide your own values:
1
2
3
4
5
6
7
enum Weapon { Axe = 5;
              Dagger; // = 6 by default (counts sequentially upward from last-defined value)
              Sword = 9;
              Mace = 11;
}
// Let's instantiate one
Weapon firstWeapon = Sword; // firstWeapon can be used as an int with value 9 

If you want to use the Weapon name as, say, its damage value, that's how you'd do it.

If you're using multiple enums, read the section of the article about enum class. It will likely save you a headache.

Edit: JLBorges answers the question more clearly and concisely. Written by a better thinker than myself.
Last edited on
> As I instantiate this class I wish to specify what type of weapon this is
> Is there any way to 'lock' a specific value to represent the class?

Yes. C++ has direct support for the notion that some objects do not undergo changes over time.
For a type calendar_date, the object next_holiday is modifiable,
while the object my_birthday is not (const calendar_date).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct weapon
{
    enum type { Axe, Dagger, Sword, Mace } ;

    weapon( type t /* , ... */ ) : type(t) /* , ... */ { /* ... */ }

    const type the_type ; // const - can't be mpdified

    // ...
};

int main()
{
    weapon rapier( weapon::Sword /* , ... */ ) ;
    // rapier.the_type never changes; it is 'locked' to weapon::Sword
}


It may be more flexible to use derived classes of weapon to represent different types of weapons.
Topic archived. No new replies allowed.