1.A bank account class
IntermediateWrite a class BankAccount with a private balance. Provide deposit(double), bool withdraw(double) (which refuses amounts above the balance) and balance() const. Deposit 1000, withdraw 300, then try to withdraw 5000.
Show hint
Keep the balance private so it can only change through methods that check the rules.
Show solution
#include <iostream>
class BankAccount {
public:
void deposit(double amount) {
if (amount > 0) balance_ += amount;
}
bool withdraw(double amount) {
if (amount <= 0 || amount > balance_) return false;
balance_ -= amount;
return true;
}
double balance() const { return balance_; }
private:
double balance_ = 0;
};
int main() {
BankAccount acc;
acc.deposit(1000);
std::cout << std::boolalpha;
std::cout << acc.withdraw(300) << ' ' << acc.withdraw(5000) << '\n';
std::cout << acc.balance() << '\n';
}true false
700