Lesson 138 +45 XP

Project 7: Bank Account Class (OOP)

Project 7: Bank Account Class (OOP)

You practiced classes; now build one with a real job. The account keeps its balance private, and the outside world only talks to it through the methods you allow.

The goal

Build a BankAccount class with a private balance, a constructor, deposit, withdraw, and a getter - then use it from main.

What you practice

  • A class with a private data member
  • A constructor that sets the starting balance
  • Methods that mutate and read the member safely
  • Using an object (and optionally a pointer to it) in main

Starter code

This is a complete, compile-able program:

#include <iostream>
using namespace std;

class BankAccount {
private:
  double balance;

public:
  BankAccount(double openingBalance) : balance(openingBalance) {}

  void deposit(double amount) {
    if (amount > 0) balance += amount;
  }

  bool withdraw(double amount) {
    if (amount > 0 && amount <= balance) {
      balance -= amount;
      return true;
    }
    return false;
  }

  double getBalance() const {
    return balance;
  }
};

int main() {
  BankAccount account(100.0);
  account.deposit(50.0);
  account.withdraw(30.0);
  cout << "Balance: " << account.getBalance() << endl;
  return 0;
}

Step-by-step

  1. Compile and run the starter; 120 should print.
  2. Try withdrawing more than the balance and confirm the money is untouched.
  3. Make the money rules yours: reject negative deposits too.
  4. Pointer practice: add BankAccount* p = &account; p->deposit(10.0); and watch the balance change.
  5. Add a method show() that prints a friendly balance line.
  6. Re-run after each change and check the totals.

Checklist

  • [ ] balance is private
  • [ ] The constructor sets the starting balance
  • [ ] deposit and withdraw protect the money with checks
  • [ ] getBalance reads the private balance
  • [ ] The object is used from main
  • [ ] The program compiles and runs

TL;DR

  • private: hides members from the outside world.
  • A constructor runs once, when the object is born.
  • Methods are the safe doorways to your data.
  • pointer->method() works like object.method() for pointers.