TExcelTAD
Home › C++ › C++ Mini Project

C++ Mini Project: Bank Account Manager

In this project you will build a small bank account manager step by step. Each step adds one idea from the course, and each step is a complete program you can run and modify. By the end you will have used classes, encapsulation, enums, vectors, maps, exceptions, smart design with const and references, and stream parsing.

What we are building: a Bank that holds several accounts. Customers can deposit, withdraw and transfer money; every account remembers its transaction history; invalid operations are rejected with clear errors; and the whole thing can be driven by a small text "script" of commands.

Step New concepts
1. A single account class, constructor, private data, const methods
2. Transaction history enum class, struct, vector, <iomanip>
3. Errors as exceptions custom exception classes, try/catch
4. A bank of accounts map, references, transfers
5. A command script istringstream, parsing, putting it all together

Note: Money is stored as whole cents in a long long. Floating-point numbers cannot represent values like 0.10 exactly, and real banking software never uses double for money.

Step 1: A single account

Start with the smallest useful piece: an account with an owner and a balance that can only change through deposit and withdraw.

cpp · try it yourself
#include <iostream>
#include <string>
using namespace std;

class Account {
public:
    Account(string owner, long long openingCents)
        : owner_(std::move(owner)), balance_(openingCents) {}

    bool deposit(long long cents) {
        if (cents <= 0) return false;
        balance_ += cents;
        return true;
    }

    bool withdraw(long long cents) {
        if (cents <= 0 || cents > balance_) return false;
        balance_ -= cents;
        return true;
    }

    const string& owner() const { return owner_; }
    long long balance() const { return balance_; }

private:
    string owner_;
    long long balance_;
};

int main() {
    Account acc("Maya", 10000);              // 100.00
    cout << boolalpha;
    cout << "deposit 25.50: " << acc.deposit(2550) << "\n";
    cout << "withdraw 500.00: " << acc.withdraw(50000) << "\n";
    cout << "withdraw 40.00: " << acc.withdraw(4000) << "\n";
    cout << acc.owner() << " has " << acc.balance() << " cents\n";
}
deposit 25.50: true
withdraw 500.00: false
withdraw 40.00: true
Maya has 8550 cents

The balance is private, so no code outside the class can set it to a nonsense value. Try adding a line acc.balance_ = -1; in main and see the compiler refuse.

Step 2: Transaction history

Next, every successful operation is recorded. An enum class names the kinds of transaction, a struct holds one record, and a vector keeps them in order. A helper function formats cents as 123.45:

cpp · try it yourself
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

string money(long long cents) {
    ostringstream out;
    out << (cents < 0 ? "-" : "") << llabs(cents) / 100 << "."
        << setw(2) << setfill('0') << llabs(cents) % 100;
    return out.str();
}

enum class TxType { Deposit, Withdrawal };

struct Transaction {
    TxType type;
    long long cents;
    long long balanceAfter;
};

class Account {
public:
    Account(string owner, long long openingCents)
        : owner_(std::move(owner)), balance_(openingCents) {}

    bool deposit(long long cents) {
        if (cents <= 0) return false;
        balance_ += cents;
        history_.push_back({TxType::Deposit, cents, balance_});
        return true;
    }

    bool withdraw(long long cents) {
        if (cents <= 0 || cents > balance_) return false;
        balance_ -= cents;
        history_.push_back({TxType::Withdrawal, cents, balance_});
        return true;
    }

    void printStatement() const {
        cout << "Statement for " << owner_ << "\n";
        for (const auto& t : history_) {
            cout << "  " << left << setw(11)
                 << (t.type == TxType::Deposit ? "deposit" : "withdrawal")
                 << right << setw(9) << money(t.cents)
                 << "  balance " << money(t.balanceAfter) << "\n";
        }
        cout << "  closing balance: " << money(balance_) << "\n";
    }

private:
    string owner_;
    long long balance_;
    vector<Transaction> history_;
};

int main() {
    Account acc("Maya", 10000);
    acc.deposit(2550);
    acc.withdraw(4000);
    acc.withdraw(99999);     // rejected, not recorded
    acc.deposit(5);
    acc.printStatement();
}
Statement for Maya
  deposit        25.50  balance 125.50
  withdrawal     40.00  balance 85.50
  deposit         0.05  balance 85.55
  closing balance: 85.55

Step 3: Errors as exceptions

Returning false is easy to ignore. For a bank, a failed withdrawal should be impossible to overlook, and the caller should learn why it failed. We switch to exceptions with a small hierarchy of error types:

cpp · try it yourself
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;

class BankError : public runtime_error {
public:
    using runtime_error::runtime_error;      // inherit the constructors
};

class InvalidAmount : public BankError {
public:
    explicit InvalidAmount(long long cents)
        : BankError("invalid amount: " + to_string(cents) + " cents") {}
};

class InsufficientFunds : public BankError {
public:
    InsufficientFunds(long long wanted, long long available)
        : BankError("insufficient funds: wanted " + to_string(wanted) +
                    ", available " + to_string(available)) {}
};

class Account {
public:
    Account(string owner, long long openingCents)
        : owner_(std::move(owner)), balance_(openingCents) {}

    void deposit(long long cents) {
        if (cents <= 0) throw InvalidAmount(cents);
        balance_ += cents;
    }

    void withdraw(long long cents) {
        if (cents <= 0) throw InvalidAmount(cents);
        if (cents > balance_) throw InsufficientFunds(cents, balance_);
        balance_ -= cents;
    }

    long long balance() const { return balance_; }

private:
    string owner_;
    long long balance_;
};

int main() {
    Account acc("Maya", 10000);
    long long attempts[] = {3000, -50, 9000, 7000};
    for (long long amount : attempts) {
        try {
            acc.withdraw(amount);
            cout << "withdrew " << amount << ", balance " << acc.balance() << "\n";
        } catch (const BankError& e) {
            cout << "rejected: " << e.what() << "\n";
        }
    }
}
withdrew 3000, balance 7000
rejected: invalid amount: -50 cents
rejected: insufficient funds: wanted 9000, available 7000
withdrew 7000, balance 0

Catching const BankError& handles both error kinds in one place, because they derive from it.

Step 4: A bank of accounts

Now a Bank class owns many accounts in a map keyed by account number. It hands out new numbers, finds accounts (throwing if a number is unknown) and performs transfers. A transfer withdraws first; if that throws, the deposit never happens, so money can't be created or lost:

cpp · try it yourself
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
#include <tuple>
using namespace std;

class BankError : public runtime_error {
public:
    using runtime_error::runtime_error;
};

class Account {
public:
    Account(string owner, long long cents) : owner_(std::move(owner)), balance_(cents) {}
    void deposit(long long c) {
        if (c <= 0) throw BankError("invalid amount");
        balance_ += c;
    }
    void withdraw(long long c) {
        if (c <= 0) throw BankError("invalid amount");
        if (c > balance_) throw BankError("insufficient funds in account of " + owner_);
        balance_ -= c;
    }
    const string& owner() const { return owner_; }
    long long balance() const { return balance_; }
private:
    string owner_;
    long long balance_;
};

class Bank {
public:
    int open(const string& owner, long long cents) {
        int number = nextNumber_++;
        accounts_.emplace(number, Account(owner, cents));
        return number;
    }

    Account& get(int number) {
        auto it = accounts_.find(number);
        if (it == accounts_.end()) throw BankError("no account #" + to_string(number));
        return it->second;
    }

    void transfer(int from, int to, long long cents) {
        Account& src = get(from);
        Account& dst = get(to);       // look up both before changing anything
        src.withdraw(cents);
        dst.deposit(cents);
    }

    long long totalDeposits() const {
        long long sum = 0;
        for (const auto& [number, acc] : accounts_) sum += acc.balance();
        return sum;
    }

    void print() const {
        for (const auto& [number, acc] : accounts_) {
            cout << "  #" << number << " " << acc.owner() << ": " << acc.balance() << "\n";
        }
        cout << "  total: " << totalDeposits() << "\n";
    }

private:
    map<int, Account> accounts_;
    int nextNumber_ = 1001;
};

int main() {
    Bank bank;
    int maya = bank.open("Maya", 50000);
    int omar = bank.open("Omar", 12000);

    bank.transfer(maya, omar, 20000);
    cout << "after first transfer:\n";
    bank.print();

    for (auto [from, to, amount] : {tuple{omar, maya, 99999LL}, tuple{maya, 4242, 100LL}}) {
        try {
            bank.transfer(from, to, amount);
        } catch (const BankError& e) {
            cout << "transfer failed: " << e.what() << "\n";
        }
    }
    cout << "after failed transfers:\n";
    bank.print();
}
after first transfer:
  #1001 Maya: 30000
  #1002 Omar: 32000
  total: 62000
transfer failed: insufficient funds in account of Omar
transfer failed: no account #4242
after failed transfers:
  #1001 Maya: 30000
  #1002 Omar: 32000
  total: 62000

The total stays at 62000 cents after the failed transfers — exactly the invariant a bank must protect. Note how get returns an Account&: callers work on the account stored inside the map, not on a copy.

Step 5: Driving the bank with commands

Finally, the bank is controlled by a script of text commands, parsed with an istringstream — the same technique you would use to read commands from a file or the keyboard. This is the complete program:

cpp · try it yourself
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;

string money(long long cents) {
    ostringstream out;
    out << (cents < 0 ? "-" : "") << llabs(cents) / 100 << "."
        << setw(2) << setfill('0') << llabs(cents) % 100;
    return out.str();
}

long long parseMoney(const string& text) {          // "12.34" -> 1234
    size_t dot = text.find('.');
    if (dot == string::npos) return stoll(text) * 100;
    string cents = text.substr(dot + 1);
    if (cents.size() == 1) cents += "0";
    return stoll(text.substr(0, dot)) * 100 + stoll(cents.substr(0, 2));
}

class BankError : public runtime_error {
public:
    using runtime_error::runtime_error;
};

class Account {
public:
    Account(string owner, long long cents) : owner_(std::move(owner)), balance_(cents) {
        log("open", cents);
    }
    void deposit(long long c) {
        if (c <= 0) throw BankError("amount must be positive");
        balance_ += c;
        log("deposit", c);
    }
    void withdraw(long long c) {
        if (c <= 0) throw BankError("amount must be positive");
        if (c > balance_) throw BankError("insufficient funds (" + money(balance_) + " available)");
        balance_ -= c;
        log("withdraw", c);
    }
    const string& owner() const { return owner_; }
    long long balance() const { return balance_; }
    void statement() const {
        cout << "  statement for " << owner_ << ":\n";
        for (const auto& line : history_) cout << "    " << line << "\n";
    }
private:
    void log(const string& what, long long c) {
        history_.push_back(what + " " + money(c) + " -> " + money(balance_));
    }
    string owner_;
    long long balance_;
    vector<string> history_;
};

class Bank {
public:
    int open(const string& owner, long long cents) {
        accounts_.emplace(next_, Account(owner, cents));
        return next_++;
    }
    Account& get(int n) {
        auto it = accounts_.find(n);
        if (it == accounts_.end()) throw BankError("unknown account #" + to_string(n));
        return it->second;
    }
    void transfer(int from, int to, long long c) {
        Account& a = get(from);
        Account& b = get(to);
        a.withdraw(c);
        b.deposit(c);
    }
    void report() const {
        long long total = 0;
        for (const auto& [n, acc] : accounts_) {
            cout << "  #" << n << " " << left << setw(6) << acc.owner()
                 << right << setw(10) << money(acc.balance()) << "\n";
            total += acc.balance();
        }
        cout << "  total       " << setw(8) << money(total) << "\n";
    }
private:
    map<int, Account> accounts_;
    int next_ = 1;
};

void run(Bank& bank, const string& script) {
    istringstream lines(script);
    string line;
    while (getline(lines, line)) {
        istringstream in(line);
        string cmd;
        in >> cmd;
        if (cmd.empty() || cmd[0] == '#') continue;
        cout << "> " << line << "\n";
        try {
            if (cmd == "open") {
                string name, amount;
                in >> name >> amount;
                int n = bank.open(name, parseMoney(amount));
                cout << "  opened #" << n << " for " << name << "\n";
            } else if (cmd == "deposit" || cmd == "withdraw") {
                int n; string amount;
                in >> n >> amount;
                Account& acc = bank.get(n);
                if (cmd == "deposit") acc.deposit(parseMoney(amount));
                else acc.withdraw(parseMoney(amount));
                cout << "  ok, balance " << money(acc.balance()) << "\n";
            } else if (cmd == "transfer") {
                int from, to; string amount;
                in >> from >> to >> amount;
                bank.transfer(from, to, parseMoney(amount));
                cout << "  ok\n";
            } else if (cmd == "statement") {
                int n;
                in >> n;
                bank.get(n).statement();
            } else if (cmd == "report") {
                bank.report();
            } else {
                cout << "  unknown command\n";
            }
        } catch (const BankError& e) {
            cout << "  error: " << e.what() << "\n";
        }
    }
}

int main() {
    const string script = R"(# open two accounts
open Maya 250.00
open Omar 40
deposit 1 19.99
withdraw 2 55.5
transfer 1 2 100.25
withdraw 3 10
fly 1 2
statement 1
report)";

    Bank bank;
    run(bank, script);
}
> open Maya 250.00
  opened #1 for Maya
> open Omar 40
  opened #2 for Omar
> deposit 1 19.99
  ok, balance 269.99
> withdraw 2 55.5
  error: insufficient funds (40.00 available)
> transfer 1 2 100.25
  ok
> withdraw 3 10
  error: unknown account #3
> fly 1 2
  unknown command
> statement 1
  statement for Maya:
    open 250.00 -> 250.00
    deposit 19.99 -> 269.99
    withdraw 100.25 -> 169.74
> report
  #1 Maya      169.74
  #2 Omar      140.25
  total         309.99

Ideas for extending the project

  1. Add an interest <account> <percent> command that adds interest to a savings account.
  2. Create a SavingsAccount that derives from Account and limits withdrawals to three per month (use a counter and a virtual withdraw).
  3. Save the bank to a file with ofstream after the script runs, and load it again with ifstream.
  4. Replace the raw std::map<int, Account> with std::map<int, std::unique_ptr<Account>> so different account types can live in one bank.
  5. Read the commands from std::cin on your own computer to make the program interactive.

Test yourself

Why does the project store money as cents in a long long instead of a double?

  1. long long is faster to print
  2. Floating-point numbers cannot represent most decimal amounts exactly
  3. double cannot be negative
  4. Maps cannot store doubles

In Bank::transfer, why are both accounts looked up before any money moves?

  1. It is faster
  2. So an unknown destination cannot cause money to be withdrawn and lost
  3. Because map requires it
  4. To sort the accounts

Why does Bank::get return Account& rather than Account?

  1. References are smaller
  2. So callers modify the account stored in the map, not a copy
  3. Because Account cannot be copied
  4. To make it const