Bank Account
Completed
Write class Account with a constructor taking the owner's name, private balance, deposit, withdraw (returns false on overdraft or non-positive amounts) and getters. Process commands and print OWNER: BALANCE at the end (2 decimals).
Input
Line 1: owner. Line 2: n. Then n lines dep X / wd X.
Output
Any rejected lines, then the summary.
Example
Input
ann 5 dep 100 wd 30.5 wd 500 dep -5 dep 10
Output
rejected rejected ann: 79.50
Editor
C++
Hints
The member initializer list : owner_(owner) sets fields before the constructor body runs.
Solution explanation
explicit stops accidental conversions like Account a = "ann";.
Show solution
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Account {
public:
explicit Account(string owner) : owner_(owner) {}
bool deposit(double amount) {
if (amount <= 0) return false;
balance_ += amount;
return true;
}
bool withdraw(double amount) {
if (amount <= 0 || amount > balance_) return false;
balance_ -= amount;
return true;
}
const string &owner() const { return owner_; }
double balance() const { return balance_; }
private:
string owner_;
double balance_ = 0;
};
int main() {
string owner;
int n;
cin >> owner >> n;
Account acc(owner);
for (int i = 0; i < n; i++) {
string cmd;
double amount;
cin >> cmd >> amount;
bool ok = cmd == "dep" ? acc.deposit(amount) : acc.withdraw(amount);
if (!ok) cout << "rejected\n";
}
cout << fixed << setprecision(2) << acc.owner() << ": " << acc.balance() << "\n";
return 0;
}