/* Simple bank account using structs and C++ * pass-by-reference. * * Note how much clearer this code is compared * to using C pointers. */ #include using namespace std; struct Account { char *firstName; char *lastName; int number; double balance; }; void Deposit(Account &act, double amount); void Withdrawal(Account &act, double amount); double Balance(Account act); void PrintInfo(Account act); int main() { Account act; // Initialize account act.firstName = "Chris"; act.lastName = "Marron"; act.number = 14314; act.balance = 0.0; // Good programmer! Uses defined functions // that include error checking PrintInfo(act); Deposit(act, 100.0); cout << "Balance is " << Balance(act) << endl; Withdrawal(act, 150.0); cout << "Balance is " << Balance(act) << endl << endl; // Bad programmer! Bypasses error checking // Can't stop this with structs act.balance -= 150.0; cout << "Balance is " << Balance(act) << endl; return 0; } void Deposit(Account &act, double amount) { // could add loging, etc. if (amount > 0.0) act.balance += amount; else cerr << "Deposit: amount must be positive." << endl; } void Withdrawal(Account &act, double amount) { // could add loging, etc. if (amount > 0.0) if (amount <= act.balance) act.balance -= amount; else cerr << "Withdrawal: insufficient funds." << endl; else cerr << "Withdrawal: amount must be positive." << endl; } double Balance(Account act) { // could add loging, etc. return act.balance; } void PrintInfo(Account act) { cout << "Account number: " << act.number << endl; cout << "Owner: " << act.firstName << " " << act.lastName << endl; cout << "Balance: " << act.balance << endl << endl; }