Learn C++ · lesson 41 of 61 · about 10 minutes
Project: Bank Account
Open the castle bank: model an account with safe deposits and withdrawals and a transaction history.
What you'll learn
- Design a class with private state
- Reject invalid operations
- Keep a history in a vector
The castle bank
The castle has a bank, and the hero opens an account in their own name. Gold can go from the pouch into the bank, but only as much as the hero has, and come back out, but only as much as the account holds. Every change goes into the account's history, and at the end the bank prints a statement like Ada the Brave: +20 -5 = 15. A request the bank turns down is reported instead of being ignored, which is why deposit() and withdraw() return a bool.
The design
Account keeps the owner, the balance in pence, and a history of changes, all private. Its public functions:
deposit(pence)andwithdraw(pence)return true if they succeededbalance()andprint_statement()only read, so they're const
Step 1: a balance only the class can change
#include <iostream>
class Account {
public:
bool deposit(int pence) {
if (pence <= 0) return false;
balance_ += pence;
return true;
}
void print() const { std::cout << balance_ << "\n"; }
private:
int balance_ = 0;
};
int main() {
Account acc;
std::cout << std::boolalpha << acc.deposit(500) << " " << acc.deposit(-5) << "\n";
acc.print();
}Output
true false
500The owner and the history
The constructor takes the owner's name, so no account exists without one. Each successful change is pushed onto a std::vector<std::string> as text like +5000, and print_statement() walks through it.
The account
#include <iostream>
#include <string>
#include <vector>
class Account {
public:
explicit Account(std::string owner) : owner_(std::move(owner)) {}
bool deposit(int pence) {
if (pence <= 0) return false;
balance_ += pence;
history_.push_back("+" + std::to_string(pence));
return true;
}
bool withdraw(int pence) {
if (pence <= 0 || pence > balance_) return false;
balance_ -= pence;
history_.push_back("-" + std::to_string(pence));
return true;
}
int balance() const { return balance_; }
void print_statement() const {
std::cout << owner_ << ":";
for (const auto& h : history_) std::cout << " " << h;
std::cout << " = " << balance_ << "\n";
}
private:
std::string owner_;
int balance_ = 0;
std::vector<std::string> history_;
};
int main() {
Account acc("Ada");
acc.deposit(5000);
acc.withdraw(2000);
std::cout << std::boolalpha << acc.withdraw(9000) << " " << acc.deposit(-5) << "\n";
acc.print_statement();
}Output
false false
Ada: +5000 -2000 = 3000Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.