codegurukool.com · Free coding tutorials & online compiler

Home › C++ Tutorial › Live project: Bank account (OOP)

Live project: Bank account (OOP)

Model a bank account with a class.

Use classes, constructors, methods and vectors to build a small bank account.

What you will build

Steps

  1. Read the class: owner, balance and log are private.
  2. The constructor sets the owner and the opening balance.
  3. Press Run and read the log.
  4. Withdraw more than the balance and see the failed entry.

Run it

Press Run to see the project work. Then change the data in the editor and run it again.

Challenge

Example code

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Account {
  string owner;
  double balance;
  vector<string> log;
public:
  Account(string o, double b) : owner(o), balance(b) {}
  void deposit(double x) {
    balance += x;
    log.push_back("deposit " + to_string((int)x));
  }
  bool withdraw(double x) {
    if (x > balance) {
      log.push_back("failed " + to_string((int)x));
      return false;
    }
    balance -= x;
    log.push_back("withdraw " + to_string((int)x));
    return true;
  }
  void show() {
    cout << owner << " balance: " << balance << endl;
    for (auto &l : log) cout << " - " << l << endl;
  }
};

int main() {
  Account a("Asha", 100);
  a.deposit(50);
  a.withdraw(30);
  a.withdraw(500);
  a.show();
  return 0;
}

Run this code in the online editor

← C++ how to: random numbers