Skip to main content

Lesson 6 of 7

Mini Project Part 3 - Bank Account with Full Encapsulation

Build a complete BankAccount class with: private data members, member initialiser list, const-correct interface, static transaction counter, RAII transaction log file (preview), and a SavingsAccount subclass preview. This integrates everything from this module.

16 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

BankAccount - Complete OOP Implementation

BankAccount - Complete OOP Implementation
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <iomanip>

class BankAccount {
    std::string  owner_;
    double       balance_;
    std::vector<std::string> history_;
    static int   total_accounts_;
    int          account_number_;

    // Private helper
    void log(const std::string& msg) {
        history_.push_back(msg);
    }

public:
    // Constructor - MIL + validation
    BankAccount(std::string owner, double initial)
        : owner_(std::move(owner))
        , balance_(initial)
        , account_number_(++total_accounts_)
    {
        if (initial < 0) throw std::invalid_argument("Initial balance < 0");
        log("Account opened with $" + std::to_string(initial));
        std::cout << "Account #" << account_number_ << " created for " << owner_ << "
";
    }

    // No copy (each account is unique)
    BankAccount(const BankAccount&)            = delete;
    BankAccount& operator=(const BankAccount&) = delete;

    ~BankAccount() {
        std::cout << "Account #" << account_number_ << " (" << owner_ << ") closed
";
    }

    // ── Mutating operations ───────────────────────────────────
    void deposit(double amount) {
        if (amount <= 0) throw std::invalid_argument("Deposit must be > 0");
        balance_ += amount;
        log("Deposited $" + std::to_string(amount));
    }

    bool withdraw(double amount) {
        if (amount <= 0) throw std::invalid_argument("Withdrawal must be > 0");
        if (amount > balance_) {
            log("Withdrawal of $" + std::to_string(amount) + " DECLINED (insufficient funds)");
            return false;
        }
        balance_ -= amount;
        log("Withdrew $" + std::to_string(amount));
        return true;
    }

    void transfer(BankAccount& to, double amount) {
        if (withdraw(amount)) {
            to.deposit(amount);
            log("Transfer $" + std::to_string(amount) + " to #" + std::to_string(to.account_number_));
        }
    }

    // ── const accessors ───────────────────────────────────────
    double             balance() const { return balance_; }
    const std::string& owner()   const { return owner_; }
    int                number()  const { return account_number_; }

    static int total_accounts() { return total_accounts_; }

    void print_statement() const {
        std::cout << std::fixed << std::setprecision(2);
        std::cout << "
=== Statement for " << owner_ << " (Acc #" << account_number_ << ") ===
";
        for (const auto& entry : history_) {
            std::cout << "  " << entry << "
";
        }
        std::cout << "  Current balance: $" << balance_ << "
";
    }
};

// Static member definition
int BankAccount::total_accounts_ = 0;

int main() {
    std::cout << "Accounts before: " << BankAccount::total_accounts() << "
"; // 0

    BankAccount alice{"Alice", 1000.0};
    BankAccount bob{"Bob",     500.0};
    std::cout << "Accounts after: " << BankAccount::total_accounts() << "
";  // 2

    alice.deposit(250.0);
    alice.withdraw(100.0);
    alice.transfer(bob, 300.0);

    bool ok = alice.withdraw(10000.0);   // declined
    std::cout << "withdraw 10000: " << (ok ? "ok" : "declined") << "
";

    alice.print_statement();
    bob.print_statement();

    try {
        BankAccount bad{"X", -500};
    } catch (const std::invalid_argument& e) {
        std::cerr << "Error: " << e.what() << "
";
    }

    return 0;
}

Common Mistakes

  • Not deleting copy constructor for accounts - if copy is allowed: `BankAccount acc2 = alice;` gives two accounts with the same account number and shared balance variable (not shared - value-copied). The account_number_ should be unique - deleting copy enforces this.
  • Catching exception in `transfer` without re-establishing state - if `deposit` somehow throws after `withdraw` succeeds, Alice lost money with Bob not gaining it. True exception-safe transfer requires a transaction mechanism or the strong exception guarantee.
  • Using global `total_accounts_` as the actual ID - if accounts are destroyed and recreated, IDs reuse numbers. A better approach: use a monotonically increasing counter and never decrement it in the destructor.

Tip

Tip

Practice Mini Project Part 3 Bank Account with Full Encapsulation in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Private State Protection, Invariant Enforcement, and Immutable Audit Log

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Part 3 Bank Account with Full Encapsulation from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Mini Project Part 3 Bank Account with Full Encapsulation is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • Build a complete BankAccount class with: private data members, member initialiser list, const-correct interface, static transaction counter, RAII transaction log file (preview), and a SavingsAccount subclass preview.
  • Not deleting copy constructor for accounts - if copy is allowed: `BankAccount acc2 = alice;` gives two accounts with the same account number and shared balance variable (not shared - value-copied). The account_number_ should be unique - deleting copy enforces this.
  • Catching exception in `transfer` without re-establishing state - if `deposit` somehow throws after `withdraw` succeeds, Alice lost money with Bob not gaining it. True exception-safe transfer requires a transaction mechanism or the strong exception guarantee.
  • Using global `total_accounts_` as the actual ID - if accounts are destroyed and recreated, IDs reuse numbers. A better approach: use a monotonically increasing counter and never decrement it in the destructor.

Topics in This Module

0/7 done