I’m sure I’m overlooking something very basic. If anyone could offer some help, or point me to a relevant thread, I’d be extremely grateful. In addition, if you need more of my code, I’d be happy to provide it.
I have a simple Bank Account program. In the main() class, I have the following function:
void deposit(const Bank bank, ofstream &outfile)
{
int requested_account, index;
double amount_to_deposit;
const Account *account;
cout << endl << "Enter the account number: "; //prompt for account number
cin >> requested_account;
index = findAccount(bank, requested_account);
if (index == -1) //invalid account
{
outfile << endl << "Transaction Requested: Deposit" << endl;
outfile << "Error: Account number " << requested_account << " does not exist" << endl;
}
else //valid account
{
cout << "Enter amount to deposit: "; //prompt for amount to deposit
cin >> amount_to_deposit;
if (amount_to_deposit <= 0.00) //invalid amount to deposit
{
outfile << endl << "Transaction Requested: Deposit" << endl;
outfile << "Account Number: " << requested_account << endl;
outfile << "Error: " << amount_to_deposit << " is an invalid amount" << endl;
}
else //valid deposit
{
outfile << endl << "Transaction Requested: Deposit" << endl;
outfile << "Account Number: " << requested_account << endl;
outfile << "Old Balance: $" << bank.getAccount(index).getAccountBalance() << endl;
outfile << "Amount to Deposit: $" << amount_to_deposit << endl;
bank.getAccount(index).makeDeposit(&amount_to_deposit); //make the deposit
outfile << "New Balance: $" << bank.getAccount(index).getAccountBalance() << endl;
}
}
return;
} // close deposit()
The issue is with the makeDeposit(&amount_to_deposit). The output file shows:
Transaction Requested: Deposit
Account Number: 1234
Old Balance: $1000.00
Amount to Deposit: $168.00
New Balance: $1000.00
Within the Account class, here is the function makeDeposit:
void Account::makeDeposit(double *deposit)
{
cout << "Account balance: " << accountBalance << endl;
accountBalance += (*deposit);
cout << "Running makeDeposit of " << *deposit << endl;
cout << "Account balance: " << accountBalance << endl;
return;
}
The console output, from the cout calls, is:
Enter the account number: 1234
Enter amount to deposit: 169
Account balance: 1000
Running makeDeposit of 169
Account balance: 1169
So, within the makeDeposit() function, it’s correctly updating the accountBalance variable. But once the function ends, it reverts back to the initial value.
I’m sure that this is elementary for more experienced programmers. Your insight would be very much appreciated.
Thanks,
Adam
It’s because you are passing Bank by value not by reference and as const. Changing
to
should fix it