Skip to content
Tutorials Center
My learning

Topics

Lesson 154 of 171 ยท Projects

Project: Bank Account System

Build a C++ bank account system in four stages - an encapsulated Account class, custom exceptions, a transaction history, polymorphic accounts and a command processor.

A bank account looks like the simplest class imaginable: a number that goes up and down. That's exactly why it's a classic project. The interesting part isn't the arithmetic. It's the rules. A balance must never change without a record of why. A withdrawal that breaks a rule must change nothing at all. Savings and checking accounts follow different rules, yet the code that moves money shouldn't need to know which kind it's dealing with. Getting those guarantees right is what object-oriented design in C++ is for.

In this project you'll build a small banking system in four stages: an encapsulated Account class, exceptions and a transaction history, a hierarchy of account types owned through std::unique_ptr, and finally a Bank that reads commands from the Input box. Every stage is a complete program that you can run and modify. Every run starts fresh, so each stage contains all the code written so far.

You'll use classes, access specifiers and invariants, constructors, enum class, exceptions and custom exception classes, inheritance, virtual functions, abstract classes, std::unique_ptr and std::map.

The rules of our bank

Before writing code, write down what must always be true. These statements become the class invariants that the code protects:

  1. Money is stored as a whole number of cents. No floating point, ever.
  2. A balance changes only through operations that append a transaction to the account's history. The history explains every cent.
  3. Amounts must be positive. A failed operation leaves the account exactly as it was.
  4. There are two account types. A checking account may go overdrawn down to a limit and pays a fee if it's negative at the end of the month. A savings account can't go negative, earns monthly interest and allows only three withdrawals per month.
  5. Accounts have unique numbers, are never copied, and are owned by the bank.

Stage 1: an encapsulated Account

The first stage answers two design questions: how to represent money, and how to stop other code from breaking the rules.

Money is an integer. A double can't represent 0.10 exactly, because it stores binary fractions. Ten deposits of ten cents add up to almost, but not quite, one dollar, and a bank that loses fractions of a cent on every operation is a bank with auditors. Storing cents in a long long makes every amount exact, and a 64-bit integer holds about 92 quadrillion dollars' worth of cents. The type alias Cents makes the intent visible in every signature (see Type Aliases), and format_money is the one place that turns cents into text.

The balance is private. If balance were a public member, any code anywhere could write account.balance = 1'000'000; and rule 3 would mean nothing. Making it private means the only way to change it is through deposit and withdraw, which check the rules. This is encapsulation: the class guards its own invariants. Read access is still easy through the balance() getter, which is const because reading shouldn't change anything (see const Member Functions).

C++ Stage 1: money in cents and a guarded balance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The first line of output shows the floating-point problem plainly: the double total prints as 0.9999999999999999 and isn't equal to 1.0. The integer version prints exactly $1.00.

Notice [[nodiscard]] on deposit and withdraw. A function that reports failure through its return value is only safe if callers look at that value. With [[nodiscard]], ignoring the result produces a compiler warning. That's why the loop writes (void)account.deposit(10);: the cast says "I'm ignoring this on purpose". Which brings us to the weakness of this design. Return codes are easy to ignore, and a bool can't say why something failed. A refused withdrawal could mean "not enough money" or "negative amount", and the caller can't tell which.

The 250'00 spelling uses digit separators (C++14) to show dollars and cents: 250'00 is just 25000 cents.

Stage 2: exceptions and a transaction history

Stage 2 makes two changes. Failed operations now throw exceptions that carry the reason, and every successful operation appends a transaction to the history (rule 2).

Why exceptions here? A withdrawal that's refused is not a normal result that the caller can quietly move past. It's a broken precondition, and the operation can't continue. An exception can't be ignored by accident: if nobody catches it, the program stops. And because exceptions are classes, each one can carry details. The program defines a small hierarchy:

  • BankError, derived from std::runtime_error, is the base for every business rule violation. Code that wants to say "any bank problem" catches BankError.
  • InsufficientFunds derives from BankError and also stores the requested and available amounts, so a caller can do something smarter than print the message.
  • Invalid arguments, such as a negative amount, throw the standard std::invalid_argument. That's a programming or input error, not a bank rule, so it deliberately sits in a different branch of the hierarchy.

Catching by const& avoids copying the exception and preserves its real type, so e.what() returns the derived class's message (see Custom Exception Classes).

The history. A Transaction records what happened (Kind, a scoped enum class), how much the balance changed (negative for money out) and the balance afterwards. Every change goes through one private function, apply. Having exactly one place that modifies balance_ makes rule 2 easy to check: read one function, and you know every change is recorded.

Look at the order inside apply. It appends the transaction first, then updates the balance. push_back may throw std::bad_alloc if memory runs out, and if that happens it leaves the vector unchanged (it has the strong guarantee). Updating balance_ afterwards can't throw. So either both happen or neither does. In the other order, a failed push_back would leave a changed balance with no record. That's rule 3 at the smallest scale (see Exception Safety and noexcept).

C++ Stage 2: exceptions and transaction history

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The output shows both failures with their reasons, and the statement lists exactly three transactions. The refused withdrawal and the rejected deposit left no trace, which is rule 3 in action: withdraw checks everything before calling apply, so when it throws, nothing has been touched yet.

The second try block shows why the hierarchy matters. deposit(-20'00) throws std::invalid_argument, which is not a BankError, so the first handler is skipped and the second one runs. Handlers are tried in order, so always list more specific exception types before more general ones.

Stage 3: checking and savings accounts

Rule 4 introduces two account types that share most behavior but differ in a few decisions: how much can be withdrawn, what happens at the end of the month, and what the account is called. That's a textbook case for inheritance with virtual functions.

Here's the design, and the reasoning behind each part:

  • Account becomes an abstract base class. It declares type_name() and end_of_month() as pure virtual (= 0), so you can't create a plain Account. Every real account must be a checking or savings account (see Abstract Classes and Interfaces).
  • withdraw stays non-virtual. It's the one function that enforces the order "validate, check the type's rules, record, then update counters", and derived classes must not be able to skip a step. Instead, it calls two protected virtual hooks: check_withdrawal (throw if this type forbids the withdrawal) and after_withdrawal (update any per-type state). This pattern is called the non-virtual interface (NVI) idiom. The base class owns the algorithm; derived classes customize only the steps it allows.
  • apply is protected, so derived classes can record interest and fees, but outside code still can't change balances without going through the rules.
  • A virtual destructor is mandatory because accounts will be deleted through Account pointers by std::unique_ptr<Account> (see Virtual Functions and Polymorphism).
  • Copying is deleted. Copying an account would duplicate its number and its money, which breaks rule 5. Deleting the copy operations also prevents accidental slicing, where copying a SavingsAccount into an Account would silently drop its savings parts.

CheckingAccount overrides check_withdrawal to allow an overdraft down to -overdraft_limit_. SavingsAccount refuses to go negative and counts withdrawals; a fourth withdrawal in one month throws WithdrawalLimitReached. At the end of the month, checking charges a fee if overdrawn, and savings adds interest and resets its counter.

The interest calculation stays in integers. The rate is stored in basis points (hundredths of a percent; 300 means 3.00% a year), and monthly interest is balance * rate / 120'000, rounded to the nearest cent by adding half the divisor before dividing.

C++ Stage 3: polymorphic accounts with unique_ptr

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The loop near the end is polymorphism at work. It calls end_of_month() on each Account without knowing or caring about its type, and the checking account charges its $25.00 fee while the savings account adds $2.35 interest (3% a year on $940.00, for one month). Adding a third account type later, say a BusinessAccount, wouldn't change that loop at all.

A few more details:

  • SavingsAccount::check_withdrawal calls Account::check_withdrawal with a qualified name. That runs the base version directly (no virtual dispatch), so savings reuses the "can't go negative" rule instead of repeating it.
  • The fee can push a checking account past its overdraft limit. That's a deliberate business decision (banks do this), and it's possible because end_of_month uses apply directly instead of withdraw. Code that bypasses a rule should do so visibly, in one place, with a reason.
  • The vector stores std::unique_ptr<Account>, not Account objects. A std::vector<Account> couldn't hold derived objects at all (and Account is abstract anyway). The unique_ptr owns each account, and when the vector is destroyed, each account is deleted through its virtual destructor.
  • Account& checking = *accounts[0]; gives a convenient name without taking ownership. The reference points at the account object on the heap, not at the vector element. If a later push_back reallocated the vector, it would move the unique_ptrs, but the accounts themselves would stay where they are, so checking would still be valid. That stability is a quiet advantage of storing pointers; with a std::vector<SomeValueType>, a reallocation invalidates every reference into it (see std::vector in Depth).

Stage 4: the bank and its commands

The final stage adds a Bank class that owns all accounts, hands out account numbers, performs transfers, and is driven by text commands from the Input box:

TEXT
open checking|savings <owner> [initial amount]
deposit <account> <amount>
withdraw <account> <amount>
transfer <from> <to> <amount>
month
statement <account>
list

Ownership and lookup. The bank stores accounts in a std::map<int, std::unique_ptr<Account>>. A map gives lookup by number and keeps list output sorted by number for free. Bank::find returns an Account& or throws AccountNotFound, so callers never deal with null pointers. Outside code gets references to accounts but can never own or delete one.

A factory function. make_account turns the word checking or savings into the right derived class and returns it as std::unique_ptr<Account>. It's the only place in the program that names the concrete types. Everything else works with Account&.

Opening is all-or-nothing. Bank::open creates the account, makes the initial deposit, and only then inserts it into the map and advances the next account number. If the deposit throws (for example, a negative amount), the unique_ptr destroys the half-built account automatically, and the bank is unchanged. That's RAII doing exception safety for you (see Destructors and RAII).

Transfers keep the strong guarantee. transfer looks up both accounts before touching either, so an unknown account number fails before any money moves. Then it withdraws from the source, which checks every rule and may throw, and only then deposits into the target. The deposit can't fail for a business reason at that point, because the amount has already been validated. (It could still throw std::bad_alloc while recording the history; a production system would catch that and reverse the withdrawal, or use a database transaction.) The transaction kinds TransferOut and TransferIn make transfers visible in both statements.

Parsing amounts exactly. parse_amount("12.50") must produce 1250 cents. Converting through double and rounding would usually work, but it's the kind of "usually" banks avoid. Instead, the function splits the text at the dot and converts both parts as integers with std::from_chars, rejecting anything with more than two decimals, signs or junk. It also caps amounts at a billion dollars so dollars * 100 can't overflow.

One error handler for the whole loop. Each command runs inside a try block in main. A broken rule, a bad number or an unknown account becomes a single error: line, and the next command runs normally. Catching std::exception there is appropriate because this is the top level of the program, where the only sensible action is to report and continue.

C++ Stage 4: a bank driven by commands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Read the output from top to bottom and match each line of input to its result. Amara's checking account goes overdrawn with the first $500 withdrawal and refuses the next $100, because only $70.75 of overdraft is left. Ben's savings account accepts three withdrawals and refuses the fourth. The bad inputs (a negative amount, an unknown account, a self-transfer, an unknown type and an amount with three decimals) are each reported in one line, and none of them changed any balance. After month, Amara's statement ends with the $25.00 overdraft fee and Ben's with his interest.

Why the Bank hands out references

find returns Account&. A reference can't be null, so callers don't need checks, and it can't be deleted, so ownership stays with the bank. Could the reference dangle? Only if the account were removed from the map while someone still held it. This bank never closes accounts, but if you add a close command (see the ideas below), keep references short-lived: look the account up, use it, and let the reference go out of scope.

Why std::map and not std::vector

Account numbers start at 1001 and might later have gaps (closed accounts). A vector indexed by number - 1001 would need to handle holes, while a map handles any key. With a handful of accounts, the speed difference is irrelevant, and the sorted order makes list nicer. For millions of accounts you'd likely pick std::unordered_map (see std::unordered_map).

Ideas to extend it

  • Close accounts. Add close <account> that only works when the balance is exactly zero, and refuses otherwise with a new BankError.
  • A third account type. Add a FixedDepositAccount that refuses all withdrawals until a number of month commands have passed. You shouldn't need to change Bank, withdraw or the command loop, only make_account.
  • Undo for transfers. Wrap the deposit in transfer with a try/catch that reverses the withdrawal and rethrows, so even std::bad_alloc can't lose money.
  • Monthly summaries. For each account, print total money in and out since the last month, using std::ranges::fold_left or std::accumulate over the history.
  • Persist the bank. Write every command to a log file, and rebuild the bank on startup by replaying the log (see Reading and Writing Text Files). Real banks call this an event log.
  • Use std::expected. Rewrite parse_amount and parse_number to return std::expected<Cents, std::string> instead of throwing, and compare which version of run_command reads better.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the project store money as a long long number of cents instead of a double?

    0.10 has no exact binary representation, so ten deposits of 0.10 add up to 0.9999999999999999. Integer cents are always exact.
  2. 2. In Account::apply, why is the transaction appended to the history before the balance is updated?

    push_back has the strong guarantee, so if it fails the vector is unchanged. Doing the non-throwing update last means the balance and the history always agree.
  3. 3. Account::withdraw is non-virtual and calls the protected virtual hooks check_withdrawal and after_withdrawal. What does this design guarantee?

    This is the non-virtual interface idiom. The base class fixes the order of steps, so no derived class can forget validation or recording, and the hooks let each type add its own checks and bookkeeping.
  4. 4. The input contains withdraw 1002 -3. What happens?

    parse_amount accepts only digits before the dot, so "-3" is rejected before the account is touched. The exception is caught in main's loop, which prints the message and continues.
  5. 5. Bank::transfer looks up both accounts before withdrawing. Why?

    Doing every check that can fail before the first change is how the transfer keeps the strong guarantee. If the lookup came after the withdrawal, a typo in the target number would make money disappear.

Summary

  • Write the rules first. Class invariants (exact money, recorded changes, all-or-nothing operations) drive every design decision.
  • Store money as integer cents behind a Cents alias, and format it in exactly one place.
  • Keep state private and change it through one function, so every change is checked and recorded.
  • Throw exceptions for broken rules; derive them from a common BankError and carry useful details. Catch by const&, most specific first.
  • Use an abstract base class with a virtual destructor, deleted copies and the non-virtual interface idiom so derived classes customize steps without bypassing the rules.
  • Own polymorphic objects with std::unique_ptr<Base>, create them in one factory function, and hand out references for use.
  • Check everything that can fail before the first change to keep the strong exception guarantee.

Next: Project: Library Catalog, where you'll store books in maps and vectors, search and sort them with ranges, and drive the catalog with commands.