Loading lessons...
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
privatedata 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
- Compile and run the starter;
120should print. - Try withdrawing more than the balance and confirm the money is untouched.
- Make the money rules yours: reject negative deposits too.
- Pointer practice: add
BankAccount* p = &account; p->deposit(10.0);and watch the balance change. - Add a method
show()that prints a friendly balance line. - Re-run after each change and check the totals.
Checklist
- [ ]
balanceisprivate - [ ] The constructor sets the starting balance
- [ ]
depositandwithdrawprotect the money with checks - [ ]
getBalancereads 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 likeobject.method()for pointers.