Bank Account Access

Bank Account Access Specifier

Design a base class BankAccount that has the following member variables:

Next, create a derived class SavingsAccount that inherits from BankAccount.

Create an object of SavingsAccount, perform some deposit and withdrawal operations, and display the balance.

Hint

Answer

#include <iostream>

class BankAccount {
private:
    std::string accountNumber;
protected:
    float balance;
public:
    BankAccount(std::string accNum, float bal) : accountNumber(accNum), balance(bal) {}

    std::string get_account_number() {
        return accountNumber;
    }
};

class SavingsAccount : public BankAccount {
public:
    SavingsAccount(std::string accNum, float bal) : BankAccount(accNum, bal) {}

    void deposit(float amount) {
        balance += amount;
        std::cout << "Deposited: $" << amount << "\n";
    }

    void withdraw(float amount) {
        if(balance >= amount) {
            balance -= amount;
            std::cout << "Withdrew: $" << amount << "\n";
        } else {
            std::cout << "Insufficient balance to withdraw $" << amount << "\n";
        }
    }

    void display_balance() {
        std::cout << "Current Balance: $" << balance << "\n";
    }
};

int main() {
    SavingsAccount myAccount("123456789", 500.0f);

    myAccount.display_balance();
    myAccount.deposit(150.0f);
    myAccount.withdraw(200.0f);
    myAccount.display_balance();

    // std::cout << myAccount.accountNumber; // This will cause an error because accountNumber is private
    // std::cout << myAccount.balance; // This will cause an error because balance is protected

    return 0;
}
Questions