// Bank Account Application using C++ Classes #include #include using namespace std; class bankaccount { private: // these variables can be used within this class only int accountnumber; string name; protected: // variables under this section could be used in subclasses double balance; public: bankaccount() // default constructor { accountnumber = 0; name = "NoName"; balance = 0; } bankaccount( int an, const string& n ) // constructor with parameters { accountnumber = an; name = n; balance = 0; } void deposit( double amount ) { balance = balance + amount; } void withdraw( double amount ) { if ( amount <= balance ) balance = balance - amount; } void setname( const string& n ) { name = n; } string getname() { return name; } void setnumber( int an ) { accountnumber = an; } int getnumber() { return accountnumber; } double getbalance() { return balance; } }; class checkingaccount: public bankaccount { private: int numchecksdrawn; void applypenalty( double amount ) { balance = balance - amount; // can access bankaccount's balance because // it is protected } public: checkingaccount() { numchecksdrawn = 0; } void withdraw( double amount ) { bankaccount::withdraw( amount ); // calls bankaccount's withdraw() method if ( getbalance() < 500 ) // below minimum balance applypenalty( 10.00 ); // apply penalty } void drawcheck( double amount ) { withdraw( amount ); numchecksdrawn++; } int getnumchecksdrawn() { return numchecksdrawn; } }; int main() { bankaccount myacct; // default constructor is invoked bankaccount namedaccount( 123, "John Smith" ); // constructor with parameters is invoked myacct.deposit( 1000.00 ); myacct.withdraw( 200.00 ); cout << myacct.getnumber() << " balance: " << myacct.getbalance() << endl; namedaccount.deposit( 5000.00 ); namedaccount.withdraw( 2000.00 ); cout << namedaccount.getnumber() << " balance: " << namedaccount.getbalance() << endl; // can't do the following (access balance directly) because the variable is private/protected // namedaccount.balance = 1000000.00; checkingaccount anotheraccount; anotheraccount.setname( "Michael Jones" ); anotheraccount.setnumber( 456 ); anotheraccount.deposit( 5000.00 ); // bankacount's deposit() anotheraccount.drawcheck( 3600.00 ); // checking account's drawcheck(); anotheraccount.withdraw( 1000.00 ); // which withdraw() method does this invoke? cout << anotheraccount.getnumber() << " balance: " << anotheraccount.getbalance() << ", checks drawn: " << anotheraccount.getnumchecksdrawn() << endl; // can't do the following because the method is private // anotheraccount.applypenalty( 10.00 ); return 0; }