LearnFrenzy
Sign in Take a free test

Constructors and Destructors · Constructor Programs · Question 3

Bank account with delegating constructors in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Write an Account class whose constructors all delegate to one validating constructor (owner must not be empty, opening balance at least the minimum), and show valid and invalid accounts.

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

class Account {
    std::string owner_, type_;
    double balance_;
public:
    Account(std::string owner, double balance, std::string type)
        : owner_(std::move(owner)), type_(std::move(type)), balance_(balance) {
        if (owner_.empty()) throw std::invalid_argument("owner required");
        double min = type_ == "current" ? 5000 : 1000;
        if (balance_ < min) throw std::invalid_argument(type_ + " needs at least " + std::to_string(static_cast<int>(min)));
    }
    Account(std::string owner, double balance) : Account(std::move(owner), balance, "savings") {}
    explicit Account(std::string owner) : Account(std::move(owner), 1000) {}
    void show() const { std::cout << owner_ << " / " << type_ << " / " << balance_ << '\n'; }
};

int main() {
    Account("Asha").show();
    Account("Ravi", 2500).show();
    Account("Meera", 8000, "current").show();
    for (auto make : {+[] { Account("", 2000); }, +[] { Account("Kabir", 3000, "current"); }}) {
        try { make(); } catch (const std::invalid_argument& e) { std::cout << "error: " << e.what() << '\n'; }
    }
    return 0;
}

Output Verified by compiling and running

Asha / savings / 1000
Ravi / savings / 2500
Meera / current / 8000
error: owner required
error: current needs at least 5000

All validation lives in one constructor; the shorter ones only supply defaults. Throwing from a constructor means no invalid Account object ever exists.

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