Build a BankAccount class

Description: Make a class BankAccount with a private balance. Add deposit and withdraw. Throw an exception for a negative deposit and for a withdraw bigger than the balance.

Hint:

  • Use std::invalid_argument and std::runtime_error.

Solution

#include <iostream>
#include <stdexcept>

class BankAccount {
public:
    void deposit(double amount) {
        if (amount <= 0) throw std::invalid_argument("Deposit must be positive");
        balance += amount;
    }
    void withdraw(double amount) {
        if (amount > balance) throw std::runtime_error("Not enough balance");
        balance -= amount;
    }
    double get_balance() const { return balance; }
private:
    double balance = 0;
};

int main() {
    BankAccount acc;
    acc.deposit(1000);
    acc.withdraw(250);
    std::cout << acc.get_balance() << '\n';
    try {
        acc.withdraw(5000);
    } catch (const std::exception& e) {
        std::cout << "Error: " << e.what() << '\n';
    }
    try {
        acc.deposit(-5);
    } catch (const std::exception& e) {
        std::cout << "Error: " << e.what() << '\n';
    }
}
Output

750
Error: Not enough balance
Error: Deposit must be positive

How it works

  • The balance is private, so only the two methods can change it, and both check the value.

Read Encapsulation.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.