fork download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. // Base class
  6. class Account {
  7. protected:
  8. string accountHolder;
  9. double balance;
  10.  
  11. public:
  12. Account(string holder, double initialBalance) {
  13. accountHolder = holder;
  14. if (initialBalance < 0) {
  15. initialBalance = 0; // Set balance to 0 if the initial value is negative
  16. }
  17. balance = initialBalance;
  18. }
  19.  
  20. virtual void deposit(double amount) {
  21. if (amount > 0) {
  22. balance += amount;
  23. cout << "Deposited: $" << amount << endl;
  24. } else {
  25. cout << "Invalid deposit amount." << endl;
  26. }
  27. }
  28.  
  29. virtual void withdraw(double amount) = 0; // Pure virtual function
  30.  
  31. virtual void displayBalance() {
  32. cout << "Account Holder: " << accountHolder << ", Balance: $" << balance << endl;
  33. }
  34.  
  35. virtual ~Account() {}
  36. };
  37.  
  38. // Derived class: SavingsAccount
  39. class SavingsAccount : public Account {
  40. public:
  41. SavingsAccount(string holder, double initialBalance)
  42. : Account(holder, initialBalance) {}
  43.  
  44. void withdraw(double amount) override {
  45. if (amount > 0 && amount <= balance) {
  46. balance -= amount;
  47. cout << "Withdrawn: $" << amount << endl;
  48. } else {
  49. cout << "Insufficient balance or invalid amount." << endl;
  50. }
  51. }
  52. };
  53.  
  54. // Derived class: CheckingAccount
  55. class CheckingAccount : public Account {
  56. public:
  57. CheckingAccount(string holder, double initialBalance)
  58. : Account(holder, initialBalance) {}
  59.  
  60. void withdraw(double amount) override {
  61. if (amount > 0 && amount <= balance) {
  62. balance -= amount;
  63. cout << "Withdrawn: $" << amount << endl;
  64. } else {
  65. cout << "Insufficient balance or invalid amount." << endl;
  66. }
  67. }
  68. };
  69.  
  70. int main() {
  71. // Create SavingsAccount
  72. SavingsAccount savings("Alice", 5000);
  73. savings.displayBalance();
  74. savings.deposit(1000);
  75. savings.withdraw(2000);
  76. savings.displayBalance();
  77.  
  78. cout << endl;
  79.  
  80. // Create CheckingAccount
  81. CheckingAccount checking("Bob", 2000);
  82. checking.displayBalance();
  83. checking.deposit(500);
  84. checking.withdraw(700);
  85. checking.withdraw(5000); // Invalid withdrawal
  86. checking.displayBalance();
  87.  
  88. return 0;
  89. }
  90.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Account Holder: Alice, Balance: $5000
Deposited: $1000
Withdrawn: $2000
Account Holder: Alice, Balance: $4000

Account Holder: Bob, Balance: $2000
Deposited: $500
Withdrawn: $700
Insufficient balance or invalid amount.
Account Holder: Bob, Balance: $1800