C++: A bank account class

Complete the class Account, whose balance is private and starts at 0. Handle these commands:

  • deposit x: add x to the balance, if x > 0; otherwise print error.
  • withdraw x: take x from the balance, if 0 < x ≤ balance; otherwise print error.
  • balance: print the balance.

What to build

A bank account class whose balance can change only through checked member functions.

Requirements

  • Keep the balance private, starting at 0.
  • Make deposit and withdraw return false when the amount is not allowed.
  • Print error whenever a command fails.

Input

The first line has q (1 ≤ q ≤ 1000). Each of the next q lines has one command; amounts are whole numbers.

Output

One line for each balance command and for each command that fails.

Constraints

1 ≤ q ≤ 1000, and the amounts are whole numbers.

Example

Input:

4
deposit 500
withdraw 800
withdraw 200
balance

Output:

error
300

Why it works

Because the balance is private, every change goes through deposit or withdraw, which check the amount first. No other code can put the account into a wrong state.

Examples

Example 1 · Input
4
deposit 500
withdraw 800
withdraw 200
balance
Expected output
error
300
Example 2 · Input
3
deposit -5
balance
withdraw 0
Expected output
error
0
error

Hints

Hint 1

Keep balance private; deposit and withdraw return false when the amount is not allowed.

Hint 2

A deposit must be positive; a withdrawal must be positive and not more than the balance.

Hint 3

Print error when deposit or withdraw returns false.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
using namespace std;

class Account {
    long long balance;
public:
    Account() : balance(0) {}
    bool deposit(long long x) {
        if (x <= 0) return false;
        balance += x;
        return true;
    }
    bool withdraw(long long x) {
        if (x <= 0 || x > balance) return false;
        balance -= x;
        return true;
    }
    long long getBalance() const {
        return balance;
    }
};

int main() {
    Account acc;
    int q;
    cin >> q;
    for (int i = 0; i < q; i++) {
        string cmd;
        cin >> cmd;
        if (cmd == "balance") {
            cout << acc.getBalance() << endl;
            continue;
        }
        long long x;
        cin >> x;
        bool ok = cmd == "deposit" ? acc.deposit(x) : acc.withdraw(x);
        if (!ok) cout << "error" << endl;
    }
    return 0;
}

Lesson: Classes and objects →