enums

Hi, I am currently learning about enumerations, and I believe I am understanding the basics, but the book goes on to talking about creating variables of the type of enum, and I am getting lost with that. I have put the code below similar to what the book has. I am wondering what I am actually doing with this code, in the line animals newAnimal am i creating another enum called newAnimal? is that enum empty? And why can i only assign a animal to that enum that was listed in the first enum?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  #include <iostream>

using namespace std;


int main()
{
	enum animals { cat, dog, goat, horse };

	animals newAnimal;

	newAnimal = dog;

	cout << newAnimal;
}
newAnimal is of your user defined type, "animals", same as int x is of type int, except int isnt a user defined type, its a standard type.

animals itself is not a variable, its a type. the enumerations inside it are constant integers, default is 0 to N, so cat == 0 and horse == 3. you can just say horse anywhere in scope as if it were a global constant value. Its a little weird because the enum constants act like "variables" (really, constants, since they do not vary, but in c++ layman's terms).

you can only assign them from that list because its of that type.

putting all that together:
horse is a constant that is 3. Its value cannot change.
newAnimal is a *variable* that can be "cat" or "horse" or "goat" etc and its value can CHANGE.
animals is a type. It has no use until you make a variable of its type; and in fact, you can make enums without a name on them if you just want a group of constant ints.
enum {this, is, legal};

enums have a bunch of cool tricks you pull; I have one at work with extra terms inside that me use subsets of the enum, for example. If the terms name array/vector locations, adding a max to the end lets you allocate arrays correctly:
enum animals { cat, dog, goat, horse, amax };
animals foo[amax];
//... oops, we forgot fish.
enum animals { cat, dog, goat, horse, fish, amax };
animals foo[amax]; //this is unchanged, and auto corrects when you compile the fix.
Last edited on
Hello DonnaPin,

To go with jonnin's explanation this may help:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  #include <iostream>

using namespace std;


int main()
{
	enum animals { cat, dog, goat, horse, totalAnimals };
    int testEnum{};
    
	animals newAnimal;

	newAnimal = dog;
    testEnum= goat;
    
	cout << "New animal = " << newAnimal;
	cout << "\nTest Enum = " << testEnum << '\n';
	
	std::cout << '\n'
	    << "Cat = " << cat
	    << "\nDog = " << dog
	    << "\nGoat = " << goat
	    << "\nHorse = " << horse;
	
	std::cout << "\nTotal animals =" << totalAnimals << '\n';
	
	newAnimal = goat;

	cout << "\nNew animal = " << newAnimal;
}


Andy
Topic archived. No new replies allowed.