How to get a void method to edit a variable

So my method takes a wallet object which stores the the amount of coins you have (e.g 7 quarters, 6 dimes, 1 nickel, 5 pennies), and adds them to another wallet object when you call the method.

In the real world, when you deposit money, whatever container you take the money from is now gone - and I've been trying to code this method to reflect that. Because at the moment it successfully adds the amount to whatever Wallet object I want, but the parameter (in this case the formal parameter 'Wallet w') still retains all of its coins.

1
2
3
4
5
6
7
  void deposit_all_change(Wallet w)
  {
    quarters += w.quarters;
    dimes += w.dimes;
    nickels += w.nickels;
    pennies += w.pennies;
  }


I've tried setting w.quarters = 0 after 'quarters += w.quarters', but
when I cout 'Wallet w' after calling my deposit method it doesn't say that the amount of quarters in Wallet w is now zero, it retains whatever amount of quarters was initialized when Wallet w was created. Was there a way to make the amount of quarters in Wallet w equal zero after depositing, or were you not allowed to do that for void methods?
Last edited on
If you want to return an integer value you make your function a integer functinon.
er, sorry. cleared up some ambiguity in the title. I know void methods don't return anything.
Pass your Wallet by reference. deposit_all_change accepts a Wallet by value (which means it receives a copy of the original object, so changes made to that copy will not be reflected in the original.)

1
2
3
4
5
6
7
8
  void deposit_all_change(Wallet & w)
  {
    quarters += w.quarters;
    // ...

    w.quarters = 0;
    // ...
  }
bingo cire! I'm going to see what other things you can do by passing stuff by reference. thanks for the quick solution!
Topic archived. No new replies allowed.