Problem displaying arrays across member functions

I have this assignment for a class to create a box of 3 types of produce using 5 types of fruits or vegetables, then allow to user to replace something from their box with one of the other produce. Here is the constructor for the box of produce

1
2
3
4
5
6
7
8
9
10
11
12
13
  Box_of_Produce::Box_of_Produce()
{

    int index = 0;
    ++counter; // counts # of boxes made 
    string produce [PRODUCE_SIZE] = { "Broccoli" , "Kale" , "Kiwi" , "Tomato" , "Tomatillo" };
    
    for (int i = 0; i < BOX_SIZE; ++i)
    {
       index = rand() % PRODUCE_SIZE; // randomly chooses the index of the fruit of vegetable
       box[i] = produce[index]; // assigns it to the box
    }
}


My problem is displaying the Produce array later when I'm asking which one they would like to substitute. I have two methods that display the arrays, one for box[] and one for produce[] here they are/

1
2
3
4
5
6
7
8
9
10
11
12
    void Box_of_Produce::Get_Produce()// This does not work, just displays blanks after each "number)"
{
     for (int i = 0; i < PRODUCE_SIZE; ++i)
        cout << (i + 1) << ") " << produce[i] << endl;
        
}

void Box_of_Produce::Get_Box()//This works fine, displays the box contents no problem
{
    for (int i =0; i < BOX_SIZE; ++i)
        cout << (i + 1) <<") " << box[i] << endl;
}


The two functions are identical, other than the array it prints, but the Get_Produce() does not work, I'm at a loss why. Is it a scope issue? if it is then why does the Get_Box() work no problem?

I had placed a for loop inside the constructor right after the produce[] initialization, and it printed fine. But calling the Get_produce() right after the loop still didn't work.

and here is the substitute method, though the problem arises before it is called so i don't think it's here.

1
2
3
4
5
6
7
8
9
10
11
12
13
void Box_of_Produce::Substitute()
{
     int replace = 0, choice = 0;
     cout << "which item would you like to replace?" << endl;
     Box_of_Produce::Get_Box();
     cin >> replace;
     
     cout << "And which item would you like to replace it with?" << endl;
     Box_of_Produce::Get_Produce();
     cin >> choice;
     
     Box_of_Produce::Set_Produce(produce[choice], replace);
}
Last edited on
I had placed a for loop inside the constructor right after the produce[] initialization, and it printed fine. But calling the Get_produce() right after the loop still didn't work.

That is because the produce that you use in the constructor is a locally declared array (the one on line 6 of the constructor) which hides the member array (which, I assume [because you sound as if you think that line 6 of your constructor initializes the member array] means you never actually initialize the member array).
Topic archived. No new replies allowed.