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
- An
Accountclass with private data - Deposit and withdraw methods
- A transaction log kept in a vector
Steps
- Read the class: owner, balance and log are private.
- The constructor sets the owner and the opening balance.
- Press Run and read the log.
- 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
- Add a
transfermethod. - Reject negative deposits.
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;
}