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 returnstrue, or changes nothing and returnsfalsewhen 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
- Declare the class above the starter code, with a
private:label and apublic: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. - Add the private data. Under
private:, declaredouble balance;, the account's hidden state. - Write the constructor under
public:. It has the name of the class and no return type, and takesinitialBalance. - Store the starting value by assigning
initialBalancetobalance. - Start
depositas avoidmethod takingamount. It changes state and returns no answer. - Guard the deposit. A one-line
if (amount <= 0) return;leaves at once for a zero or negative amount. - Add the amount to
balancewith+=. Only positive amounts reach this line. - Start
withdrawas aboolmethod takingamount. - Guard the withdrawal. Return
falsewhenamount <= 0 || amount > balance. Using>and not>=matters: asking for exactly the whole balance is allowed. - Subtract the amount from
balancewith-=. - Return
true, because reaching this line means the withdrawal happened. - Start
getBalanceas a method returningdoublewith no parameters. - 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:andpublic:are labels. Everything after a label has that access until the next label. In aclass, 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
ifwithout braces runs only the next statement. It is fine for a short guard such asif (amount <= 0) return;, but add braces as soon as the body grows. coutprints adoublewithout trailing zeros. The value 120 appears as120, so no cast is needed for the expected output.
Edge cases and common mistakes
- Refusing the whole balance. With
amount >= balancein the guard, the last withdrawal of 120 would be refused. The comparison must beamount > balance. - Zero and negative amounts. Without the
amount <= 0check,deposit(-20)would lower the balance, andwithdraw(-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
withdrawreturnsfalseand a successful one returnstrue. Swapping them makes the driver printWithdrew allat 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
privateand 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
boolfrom an action that can fail, so callers can tell what happened.
