Start learning free

LESSON 64 OF 69 · PROJECTS: OBJECT-ORIENTED

Bank Account in C++: Encapsulation with a Private Balance

Practice Read the full explanation

Build a BankAccount class that keeps its balance private and lets other code change it only through methods that check the rules. This is encapsulation: the object protects its own data.

Private balance. Put the double balance member in a private: section and the methods in a public: section, so only the class can touch the balance.

What the class must have (C++):

  • BankAccount(double initialBalance): creates an account that starts with the given balance.
  • void deposit(double amount): adds amount to the balance. If amount is zero or negative, do nothing (no error, the balance stays the same).
  • bool withdraw(double amount): if amount is zero or negative, or larger than the balance, change nothing and return false. Otherwise subtract it from the balance and return true. Withdrawing exactly the whole balance is allowed (the balance becomes 0).
  • double getBalance(): returns the current balance. It is the only way for outside code to read it.

cout prints the double 120 as 120, so no cast is needed.

The driver. The driver at the end of the starter code is already written and uses your class. It runs these checks:

class Solution {
public:
    void mainFunction() {
        BankAccount account(100);
        account.deposit(50);
        account.withdraw(30);
        account.withdraw(200);
        cout << "Balance: " << account.getBalance() << endl;
        account.deposit(-20);
        account.deposit(0);
        account.withdraw(-5);
        cout << "Balance: " << account.getBalance() << endl;
        if (account.withdraw(120)) {
            cout << "Withdrew all" << endl;
        }
        cout << "Balance: " << account.getBalance() << endl;
        if (!account.withdraw(1)) {
            cout << "Rejected" << endl;
        }
    }
};

Walk through it: start with 100, deposit 50 (150), withdraw 30 (120), withdraw 200 is refused (still 120). Then deposit -20, deposit 0 and withdraw -5 are all ignored (still 120). Withdrawing 120 succeeds and empties the account, so the balance is 0, and withdrawing 1 more is refused.

Expected output:

Balance: 120
Balance: 120
Withdrew all
Balance: 0
Rejected

Both deposit and withdraw start with a guard that rejects amount <= 0. Write the guard first, then the change to the balance.

double balance; under private:, and in the constructor balance = initialBalance;. Remember the semicolon after the closing brace of the class.

if (amount <= 0 || amount > balance) return false;, then balance -= amount; and return true;.

class BankAccount {
private:
    double balance;
public:
    BankAccount(double initialBalance) {
        balance = initialBalance;
    }

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

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

    double getBalance() {
        return balance;
    }
};

class Solution {
public:
    void mainFunction() {
        BankAccount account(100);
        account.deposit(50);
        account.withdraw(30);
        account.withdraw(200);
        cout << "Balance: " << account.getBalance() << endl;
        account.deposit(-20);
        account.deposit(0);
        account.withdraw(-5);
        cout << "Balance: " << account.getBalance() << endl;
        if (account.withdraw(120)) {
            cout << "Withdrew all" << endl;
        }
        cout << "Balance: " << account.getBalance() << endl;
        if (!account.withdraw(1)) {
            cout << "Rejected" << endl;
        }
    }
};

STEP 1 OF 13
    Ctrl + Enter to check

    C++ · PROJECTS: OBJECT-ORIENTED

    Bank Account in C++, explained

    Problem overview

    You build a BankAccount class whose balance is a private double. Code outside the class can't read or write it directly. It has to go through four public members:

    • BankAccount(double initialBalance) creates an account with a starting balance.
    • void deposit(double amount) adds money, but silently ignores an amount that is zero or negative.
    • bool withdraw(double amount) removes money and returns true, or changes nothing and returns false when the amount is zero, negative or larger than the balance.
    • double getBalance() is the only way to read the balance.

    This is encapsulation: the object protects its own data, so the rules can't be bypassed. The code at the bottom of the starter runs a sequence of calls. It starts with 100, deposits 50 and withdraws 30, leaving 120. A withdrawal of 200 is refused, so the balance stays 120. A deposit of -20, a deposit of 0 and a withdrawal of -5 are all ignored. Withdrawing exactly 120 succeeds and empties the account, and withdrawing 1 more is refused. The result:

    Balance: 120
    Balance: 120
    Withdrew all
    Balance: 0
    Rejected

    Approach: guard first, then change

    Both deposit and withdraw follow the same shape: check whether the request is valid, leave early if it isn't, and only then touch the balance. Putting the guard first means the line that changes the balance can assume the amount is acceptable, so it needs no else and no nesting.

    The two methods differ in how they report a refusal. A rejected deposit just returns, because the statement says nothing should happen and gives the caller no answer. A rejected withdrawal returns false, so the caller can tell whether the money left the account. A successful one returns true.

    The balance lives under private:, and that is what makes the guards worth writing. If balance were public, any code could do account.balance = -500 and skip every check. With it private, the compiler refuses that line. Declaring a BankAccount and then writing a.balance = 1e6; produces:

    error: 'double BankAccount::balance' is private within this context

    Step by step

    1. Declare the class above the starter code, with a private: label and a public: label, and close it with };. The semicolon after the brace is required for a class in C++; leaving it out is a common compile error.
    2. Add the private data. Under private:, declare double balance;, the account's hidden state.
    3. Write the constructor under public:. It has the name of the class and no return type, and takes initialBalance.
    4. Store the starting value by assigning initialBalance to balance.
    5. Start deposit as a void method taking amount. It changes state and returns no answer.
    6. Guard the deposit. A one-line if (amount <= 0) return; leaves at once for a zero or negative amount.
    7. Add the amount to balance with +=. Only positive amounts reach this line.
    8. Start withdraw as a bool method taking amount.
    9. Guard the withdrawal. Return false when amount <= 0 || amount > balance. Using > and not >= matters: asking for exactly the whole balance is allowed.
    10. Subtract the amount from balance with -=.
    11. Return true, because reaching this line means the withdrawal happened.
    12. Start getBalance as a method returning double with no parameters.
    13. Return balance. Outside code gets a copy of the number, so it can read the balance but can't change it through the result.

    The solution in C++

    class BankAccount {
    private:
        double balance;
    public:
        BankAccount(double initialBalance) {
            balance = initialBalance;
        }
    
        void deposit(double amount) {
            if (amount <= 0) return;
            balance += amount;
        }
    
        bool withdraw(double amount) {
            if (amount <= 0 || amount > balance) return false;
            balance -= amount;
            return true;
        }
    
        double getBalance() {
            return balance;
        }
    };
    
    class Solution {
    public:
        void mainFunction() {
            BankAccount account(100);
            account.deposit(50);
            account.withdraw(30);
            account.withdraw(200);
            cout << "Balance: " << account.getBalance() << endl;
            account.deposit(-20);
            account.deposit(0);
            account.withdraw(-5);
            cout << "Balance: " << account.getBalance() << endl;
            if (account.withdraw(120)) {
                cout << "Withdrew all" << endl;
            }
            cout << "Balance: " << account.getBalance() << endl;
            if (!account.withdraw(1)) {
                cout << "Rejected" << endl;
            }
        }
    };
    

    C++ details worth knowing

    • private: and public: are labels. Everything after a label has that access until the next label. In a class, members are private by default, but writing the labels out makes the intent clear.
    • The constructor assigns in its body. That works for this lesson. C++ code often uses a member initialiser list instead, BankAccount(double initialBalance) : balance(initialBalance) {}, which does the same job.
    • A one-line if without braces runs only the next statement. It is fine for a short guard such as if (amount <= 0) return;, but add braces as soon as the body grows.
    • cout prints a double without trailing zeros. The value 120 appears as 120, so no cast is needed for the expected output.

    Edge cases and common mistakes

    • Refusing the whole balance. With amount >= balance in the guard, the last withdrawal of 120 would be refused. The comparison must be amount > balance.
    • Zero and negative amounts. Without the amount <= 0 check, deposit(-20) would lower the balance, and withdraw(-5) would raise it.
    • Changing state before checking. Subtracting first and validating afterwards leaves the balance wrong after a refusal. Validate first.
    • Returning the wrong answer from a refusal. A refused withdraw returns false and a successful one returns true. Swapping them makes the driver print Withdrew all at the wrong time.
    • A missing semicolon after the class. The compiler then reports errors that point at the code below the class, which can be confusing.

    Testing

    Besides the driver, try fractional amounts. An account created with 0.5 that receives a deposit of 0.25 has a balance of 0.75. Withdrawing 0.75 then succeeds and returns 1 when printed, leaving a balance of 0. On an account with 100, withdraw(100.5) gives 0 (refused), withdraw(100) gives 1 and the balance ends at 0:

    0.75
    1 0
    0 1 0

    The first line is the balance after the deposit. The second line is the result of withdraw(0.75) followed by the balance. The third line holds the two withdrawals on the account with 100 and its final balance. Printing a bool with cout shows 1 for true and 0 for false.

    Key takeaways

    • Keep data private and expose it through public methods that enforce the rules.
    • Validate first and return early; change the state only when the request is valid.
    • Return a bool from an action that can fail, so callers can tell what happened.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free