I have a PiggyBank class that stores "Coins" with the functions DropIn and GrabOut. The functions will store a pointer to the "Coins" in an growable array of pointers. (CoinStorage**) The functions look like this:
DropIn is passed the array address, size, and a pointer to the coin that is supposed to be "Dropped In".
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
bool PiggyBank::DropIn(Coin** coinStorage, int& size, Coin* coin) {
Coin** temp = 0;
temp = new Coin* [size+1];
if(!temp)
return false;
for(int x=0; x<size; x++)
temp[x] = coinStorage[x];
temp[size] = coin;
size++;
if(coinStorage)
delete [] coinStorage;
coinStorage = temp;
return true;
}
|
GrabOut is passed the array address and size, makes a copy of the passed array of pointers with size-1, and returns the Coin* that was "removed" from the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
Coin* PiggyBank::GrabOut(Coin** coinStorage, int& size) {
if(size) {
Coin* save = coinStorage[size-1];
Coin** temp = new Coin* [size-1];
for(int x=0; x<size-1; x++)
temp[x] = coinStorage[x];
size--;
if(coinStorage)
delete [] coinStorage;
coinStorage = temp;
return save;
}
else {
cerr << "GrabOut(): No coins to grab!\n";
return 0;
}
}
|
My problem is that it appears as though the functions are not actually changing coinStorage "out of scope", because when I call DropIn() twice, on the second call, I assumed that the value from the first call should be in coinStorage[0], but it is not. What am I missing here?
One solution was for me to modify DropIn() to return temp** instead of a bool, and have the storage = the returned ** outside of the function.. but I'm still curious why my original method didn't work.
Thanks in advance for any help!