LearnFrenzy
Sign in Take a free test

Encapsulation · Encapsulation Programs · Question 1

Bank account with a read-only transaction history in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Write a BankAccount whose balance can change only through deposit and withdraw (validated), which records every successful transaction, and exposes the history read-only. Process commands from the input.

Solution
main.cpp
#include <iostream>
#include <span>
#include <string>
#include <vector>

class BankAccount {
public:
    struct Txn { char type; double amount; double balance_after; };
private:
    double balance_ = 0;
    std::vector<Txn> history_;
    void record(char t, double a) { history_.push_back({t, a, balance_}); }
public:
    bool deposit(double a) {
        if (a <= 0) return false;
        balance_ += a; record('D', a);
        return true;
    }
    bool withdraw(double a) {
        if (a <= 0 || a > balance_) return false;
        balance_ -= a; record('W', a);
        return true;
    }
    double balance() const { return balance_; }
    std::span<const Txn> history() const { return history_; }
};

int main() {
    BankAccount acc;
    std::string cmd;
    double amt;
    while (std::cin >> cmd >> amt) {
        bool ok = cmd == "deposit" ? acc.deposit(amt) : acc.withdraw(amt);
        if (!ok) std::cout << "rejected: " << cmd << ' ' << amt << '\n';
    }
    for (const auto& t : acc.history()) std::cout << t.type << ' ' << t.amount << " -> " << t.balance_after << '\n';
    std::cout << "balance " << acc.balance() << '\n';
    return 0;
}

Output Verified by compiling and running

rejected: withdraw 9000
rejected: deposit -20
D 5000 -> 5000
W 1500 -> 3500
W 500 -> 3000
balance 3000

The balance and history are private and change together in one place, so they can never disagree. history() hands out a read-only span: callers can audit transactions but not forge them.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links