LearnFrenzy
Sign in Take a free test

Abstraction · Abstraction Programs · Question 1

Bank account abstraction with deposit and withdraw in C++ Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Write a BankAccount class that stores money in paise privately and offers deposit, withdraw (refusing overdrafts) and a formatted balance; process a list of transactions.

Solution
main.cpp
#include <format>
#include <iostream>
#include <string>

class BankAccount {
    long paise_ = 0;
public:
    bool deposit(double rupees) {
        if (rupees <= 0) return false;
        paise_ += static_cast<long>(rupees * 100 + 0.5);
        return true;
    }
    bool withdraw(double rupees) {
        long p = static_cast<long>(rupees * 100 + 0.5);
        if (p <= 0 || p > paise_) return false;
        paise_ -= p;
        return true;
    }
    std::string balance() const { return std::format("Rs {}.{:02}", paise_ / 100, paise_ % 100); }
};

int main() {
    BankAccount acc;
    struct Tx { char type; double amount; } txs[] = {{'D', 1500.50}, {'W', 200.25}, {'W', 5000}, {'D', -10}, {'W', 300}};
    for (const auto& t : txs) {
        bool ok = t.type == 'D' ? acc.deposit(t.amount) : acc.withdraw(t.amount);
        std::cout << std::format("{} {:>8.2f} {:<8} {}\n", t.type, t.amount, ok ? "ok" : "refused", acc.balance());
    }
    return 0;
}

Output Verified by compiling and running

D  1500.50 ok       Rs 1500.50
W   200.25 ok       Rs 1300.25
W  5000.00 refused  Rs 1300.25
D   -10.00 refused  Rs 1300.25
W   300.00 ok       Rs 1000.25

Storing paise as an integer avoids floating-point rounding, and users never see it: they work in rupees through deposit/withdraw, and the class enforces "no overdraft, no negative deposits".

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links