C++C++ · Lesson 8 of 9
Mini Project: Bank Account System
Let's put it all together: a small bank account system using classes, vectors, exceptions, and file I/O.
C++
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#include <algorithm>
#include <iomanip>
using namespace std;
struct Transaction {
string type;
double amount;
double balance_after;
};
class Account {
string id;
string owner;
double balance;
vector<Transaction> history;
public:
Account(const string& id, const string& owner, double initial = 0.0)
: id(id), owner(owner), balance(initial) {}
void deposit(double amount) {
if (amount <= 0) throw invalid_argument("Deposit amount must be positive");
balance += amount;
history.push_back({"deposit", amount, balance});
}
void withdraw(double amount) {
if (amount <= 0) throw invalid_argument("Withdrawal amount must be positive");
if (amount > balance) throw runtime_error("Insufficient funds");
balance -= amount;
history.push_back({"withdrawal", amount, balance});
}
void printStatement() const {
cout << "
=== Account Statement ===
";
cout << "ID: " << id << " | Owner: " << owner << "
";
cout << fixed << setprecision(2);
cout << "Balance: $" << balance << "
";
cout << left << setw(12) << "Type"
<< right << setw(10) << "Amount"
<< right << setw(12) << "Balance" << "
";
cout << string(36, '-') << "
";
for (const auto& t : history) {
cout << left << setw(12) << t.type
<< right << setw(10) << t.amount
<< right << setw(12) << t.balance_after << "
";
}
}
double getBalance() const { return balance; }
const string& getOwner() const { return owner; }
};
int main() {
Account acc("ACC001", "Alice", 1000.0);
try {
acc.deposit(500);
acc.withdraw(200);
acc.deposit(1000);
acc.withdraw(750);
acc.withdraw(5000); // this will throw
} catch (const runtime_error& e) {
cout << "Transaction failed: " << e.what() << "
";
}
acc.printStatement();
return 0;
}Bash
g++ -std=c++17 -o bank bank.cpp
./bank