Chapter 6: Problem 9
Give an example where passing an argument by reference would be useful.
Short Answer
Expert verified
Question: Provide an example where passing an argument by reference is useful and explain why it's useful in that example.
Answer: In a banking program, where we need to transfer money between two accounts, passing arguments by reference is useful. It enables the function to modify the original data, updating the balances of both the sender and receiver accounts without creating new copies of the data, making the process more efficient. For example:
```cpp
struct Account {
int id;
double balance;
};
void transfer(Account &from, Account &to, double amount) {
from.balance -= amount;
to.balance += amount;
}
```
Here, the `transfer` function takes in two account objects by reference and directly updates their balances to reflect the transaction, avoiding unnecessary overhead.