Question 1
Back to Exercise
Write a BankAccount class with private balance, deposit and withdraw functions that reject invalid amounts, and a transaction count. Process commands from the input (D amount / W amount).
Solution
#include <iostream>
#include <string>
class BankAccount {
std::string owner_;
double balance_ = 0;
int transactions_ = 0;
public:
explicit BankAccount(std::string owner) : owner_(std::move(owner)) {}
bool deposit(double amt) {
if (amt <= 0) return false;
balance_ += amt; ++transactions_;
return true;
}
bool withdraw(double amt) {
if (amt <= 0 || amt > balance_) return false;
balance_ -= amt; ++transactions_;
return true;
}
double balance() const { return balance_; }
int transactions() const { return transactions_; }
};
int main() {
BankAccount acc("Asha");
char op;
double amt;
while (std::cin >> op >> amt) {
bool ok = op == 'D' ? acc.deposit(amt) : acc.withdraw(amt);
std::cout << op << ' ' << amt << (ok ? " ok" : " rejected") << '\n';
}
std::cout << "balance " << acc.balance() << ", " << acc.transactions() << " transactions\n";
return 0;
}
D 5000 ok W 1200 ok W 9000 rejected D -50 rejected W 800 ok balance 3000, 3 transactions
All rules live inside the class, so the balance can never become negative and only successful operations are counted.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!