// A bank account class #include "stdafx.h" #include #include #include class Account { // private members are those that cannot be changed directly by the owner // of the account. The bank has access to them and may change them. private: // the interest rate both constant, and static. This means the value // is the same (const) for all instances of the class, so we only need // one version (static) static const double interestRate; // these variables are visible to all types of bank accounts protected: double balance; std::string name; public: // public access // here the public or account user can change the // balance only by depositing cash (using deposit function) // or by withdrawing cash (using withdraw) // now virtual to allow overloading virtual void withdraw(double amount) // withdraw cash { balance = balance - amount;} void deposit(double amount) // deposit cash { balance = balance + amount;} // now virtual to allow overloading virtual void endYear() // pay interest at the end of the Year { balance = (1+interestRate)*balance; } void printBalance() { std::cout << name <<"'s balance is " << balance << " \n"; } // constructor function, can't use defaults now // as we need to specify a name when we open the account Account(int initial_balance,std::string name_) { balance = initial_balance; name=name_;} }; // static members must be initialised outside the class const double Account::interestRate=0.05; class SavingsAccount: public Account { static const double interestRate; public: void withdraw(double amount) // withdraw cash { if(balance-amount<0.){ std::cout << " Can't withdraw that amount \n"; return; } balance = balance - amount; } // this is overloaded so that we use the savings account interestRate void endYear() // pay interest at the end of the Year { balance = (1+interestRate)*balance; } // new constructor must also construct underlying account // in the initialisation list SavingsAccount(int initial_balance,std::string name_) :Account(initial_balance,name_){} }; // static members must be initialised outside the class const double SavingsAccount::interestRate=0.1; // make a Bank class to store a set of bank accounts class Bank { //make everything public at the start public: // storage for the accounts. Now store pointers // so that the account may be any type we specify std::vector accounts; // pay interest into all accounts void endYear() { for(int i=0;iendYear(); } // print balance for all accounts void printBalance() { for(int i=0;iprintBalance(); } // need a deconstructor to delete accounts when the bank closes ~Bank(){ std::cout << " Close all accounts\n"; for(int i=0;ideposit(100); // deposit some money into second account hsbc.accounts[1]->deposit(50); // pay interest into all accounts hsbc.endYear(); } // display balance for all accounts hsbc.printBalance(); }