#include <iostream>
#include <string>
using namespace std;
// Base class
class Account {
protected:
string accountHolder;
double balance;
public:
Account(string holder, double initialBalance) {
accountHolder = holder;
if (initialBalance < 0) {
initialBalance = 0; // Set balance to 0 if the initial value is negative
}
balance = initialBalance;
}
virtual void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited: $" << amount << endl;
} else {
cout << "Invalid deposit amount." << endl;
}
}
virtual void withdraw(double amount) = 0; // Pure virtual function
virtual void displayBalance() {
cout << "Account Holder: " << accountHolder << ", Balance: $" << balance << endl;
}
virtual ~Account() {}
};
// Derived class: SavingsAccount
class SavingsAccount : public Account {
public:
SavingsAccount(string holder, double initialBalance)
: Account(holder, initialBalance) {}
void withdraw(double amount) override {
if (amount > 0 && amount <= balance) {
balance -= amount;
cout << "Withdrawn: $" << amount << endl;
} else {
cout << "Insufficient balance or invalid amount." << endl;
}
}
};
// Derived class: CheckingAccount
class CheckingAccount : public Account {
public:
CheckingAccount(string holder, double initialBalance)
: Account(holder, initialBalance) {}
void withdraw(double amount) override {
if (amount > 0 && amount <= balance) {
balance -= amount;
cout << "Withdrawn: $" << amount << endl;
} else {
cout << "Insufficient balance or invalid amount." << endl;
}
}
};
int main() {
// Create SavingsAccount
SavingsAccount savings("Alice", 5000);
savings.displayBalance();
savings.deposit(1000);
savings.withdraw(2000);
savings.displayBalance();
cout << endl;
// Create CheckingAccount
CheckingAccount checking("Bob", 2000);
checking.displayBalance();
checking.deposit(500);
checking.withdraw(700);
checking.withdraw(5000); // Invalid withdrawal
checking.displayBalance();
return 0;
}