Back to track
#110 Medium Object-Oriented C++

Encapsulation

Open the editor

Problem

Make data private and expose safe methods only.

Input

No input.

Output

Exactly what the described program prints.

Hints

  1. 1

    Protect from negative withdrawals

  2. 2

    Store balance in private

Worked solution

Reference solution

One correct implementation. Alternative approaches that satisfy the constraints are equally valid — the reviewer judges behaviour, not style.

#include <iostream>
using namespace std;

class BankAccount {
public:
  void deposit(int amount) {
    if (amount > 0) {
      balance_ += amount;
    }
  }

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

  int balance() const { return balance_; }

private:
  int balance_ = 0;
};

int main() {
  BankAccount a;
  a.deposit(100);
  a.withdraw(30);
  cout << a.balance() << '\n';
  return 0;
}

© 2026 ChitChat