How to declare a class object with an array object of another class?

How could I declare an object 'transaction1' of class 'CashRegister' with an object 'inventory' of an array from another class?

I learned that by putting 'inventory[5] would do so but it ends with an error.

1
2
3
4
5
6
7
8
9
10
11

const int NUM_ITEMS = 5;
InventoryItem inventory[NUM_ITEMS] = {
InventoryItem("Hammer", 6.95, 12),
InventoryItem("Wrench", 8.75, 20),
InventoryItem("Pliers", 3.75, 10),
InventoryItem("Ratchet", 7.95, 14),
InventoryItem("ScrewDriver", 2.75, 22) };

CashRegister transaction1(mainDesc, mainNumbers, inventory[1]);


1
2
3
4
5
6
7
8
9
10

CashRegister::CashRegister(const string orderdesc, const double ordernumbers, const  InventoryItem &inventory)
	: orderDesc (orderdesc),
	 orderNumbers(ordernumbers),
	 inventoryComp(inventory)
{
   cout << "meow";
}

The problem here is that you're accessing memory that isn't yours. Array indexes start at zero, so you're actually accessing the element after that. (That behavior is undefined)

Example:

1
2
3
4
int my_array[5] = {};

my_array[0] = 10; // Accessing 1st element
my_array[4] = 20; // Accessing 5th element 
Last edited on
Topic archived. No new replies allowed.