Bank Account Access Specifier
Design a base class BankAccount that has the following member variables:
accountNumber(private)balance(protected)
Next, create a derived class SavingsAccount that inherits from BankAccount.
- Implement a method
deposit(float amount)inSavingsAccountthat adds money to thebalance. - Implement a method
withdraw(float amount)inSavingsAccountthat subtracts money from thebalancebut ensures it doesn’t go below zero. - Implement a method
display_balance()inSavingsAccountthat prints the current balance but does not reveal theaccountNumber.
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;
}