Array of structs as a class member variable: initialization

The problem states:
Create a drink machine simulator class. The class should use a structure that has:
Drink name
Drink price
# of drinks in the machine

The class should have an array of five of these structures.

The only thing that differs of the five types is the names and one of them costs $1 instead of $0.75.

Wondering if there is a cleaner way to initialize the structures than this.

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

const int CAPACITY = 5;

struct Soda
{
	string name;
	double price;
	int quantity;

	Soda( string n = "", double p = .75, int q = 20 )
	{	name = n;
		price = p;
		quantity = q;
	}

};

class DrinkMachine
{
	public:
		Soda selection[CAPACITY];

	public:
		void displayChoices();	//displays a menu of drink names and prices
		void buyDrink();		//handles a sale
		
		//constructors
		DrinkMachine()
		{
			selection[0].name = "Cola";
			selection[1].name = "Root Beer";
			selection[2].name = "Orange Soda";
			selection[3].name = "Grape Soda";
			selection[4].name = "Bottled Water";
			selection[4].price = 1.00;
		}
	
	public:
		void printContents(); //driver function
};

int main()
{
	DrinkMachine mySodas;

	cout << fixed << showpoint << setprecision(2);
	
	mySodas.printContents();
	
	system("pause");
	return 0;
}

void DrinkMachine::displayChoices()
{
	return;
}

void DrinkMachine::buyDrink()
{
	return;
}

void DrinkMachine::printContents()
{
	for( int i = 0; i < CAPACITY; i++)
		cout << setw(15) << left << selection[i].name << "\t" << selection[i].price << "\t" << selection[i].quantity << endl;
	return;
}
From a maintainability standpoint, it would be better if you used Soda's constructor on lines 34-39, though it will be ever so slightly slower.

While there are ways to initialize arrays using initializer lists (there was a recent post on this), those ways are ugly.
Topic archived. No new replies allowed.