Passing an Enum with a function to control a switch

closed account (NU9GNwbp)

Can anyone look at this and help me with what is wrong. This code works, sort of- it gives me an error saying that the return choice; is not being initialized.

Above my class I declare the enum like so:

enum MediaType {AUDIO_CASSETTE = 1, AUDIO_CD, VIDEO_VHS, VIDEO_DVD};


Here are the implementations for the functions in question: specifically GetMedia and Addmedia.

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
31
32
33
34
35

MediaType MediaCollection::GetMediaTypeSelection(){
	
MediaType choice;

int menuChoice = 0;

cout << "Please make a selection (1-4). > ";
cin >> menuChoice;

// Based on menu choice, assign selection to its
// enumerated type, and return
switch (menuChoice)
{
case 1:
choice = AUDIO_CASSETTE;
break;
case 2:
choice =AUDIO_CD;
break;
case 3:
choice =VIDEO_VHS;
break;
case 4:
choice =VIDEO_DVD;
break;
default:
cout << "Invalid choice for media." << endl;
	}

return choice;
}


Last edited on
closed account (zb0S216C)
Based on what you said, the compiler doesn't like the fact that a enumeration object hasn't been initialised. Try initialising the enumeration objects with one of those enumerators.

Edit: Suggestion:

Maybe you can add an additional enumerator to the MediaType enumeration list, such as UNKNOWN_TYPE. It could be used for initialisation, and could also be used to indicate an unspecified choice, or "type not yet chosen".

Wazzak
Last edited on
brb00136 wrote:
Can anyone look at this and help me with what is wrong. This code works, sort of- it gives me an error saying that the return choice; is not being initialized.


Try initializing the variable declared on line 11 to a valid enum integer.
closed account (NU9GNwbp)
I tried setting choice = AUDIO_CASSETTE however when I un-commented the other cases under the Switch statement it would only create AUDIO_CASSETTES

Edit:

Maybe you can add an additional enumerator to the MediaType enumeration list, such as UNKNOWN_TYPE. It could be used for initialisation, and could also be used to indicate an unspecified choice, or "type not yet chosen".

So would UNKNOWN_TYPE take the place of default under the switch?
Last edited on
closed account (zb0S216C)
You're missing your break statements after each case. Also, you've got yourself a memory leak. Allow me to elaborate:

Each case allocates memory when it's executed. Since there's no break statement between each case, the compiler will move onto the next case, which will overwrite Collection's previous memory; which in turn, creates a memory leak.

brb000136 wrote:
So would UNKNOWN_TYPE take the place of default under the switch?

I guess so; there's no harm in it.

Wazzak
Last edited on
closed account (NU9GNwbp)
wow: I have been staring at this thing for over 10 hours. Thank you for the quick responses!
Topic archived. No new replies allowed.