Docstoc

Inheritance

Document Sample
Inheritance Powered By Docstoc
					C++ Programming for Graphics
        Inheritance

     Bank account examples
Example account hierarchy
  • account relationships:


                ACCOUNT



    SAVINGS                  CHEQUE



    TIME_ACCT
    About the classes

• Account is the most general

         methods include accept balance, return balance
         members include balance


 • SAVINGS provides interest and withdrawal
 • CHEQUE provides cheque facilities, there is a charge per cheque
       if balance is below limit
 •TIME_ACCT only accumulated interest can be withdrawn
  The Declarations

• In the header file (            .h)

      class ACCOUNT{
      protected: double dbalance;
      public:
              ACCOUNT(double bal = 0.0) { balance = bal;}
              void deposit( double amount) {dbalance += amount;}
              double get_balance() const {return dbalance;}
      };
     Main points

The functions are so small their definitions
can appear in the header

 protected - means that any function in this
class or any function in a derived class can
gain access
  Main points cont.

On construction the ACCOUNT can be
sent a value, if no value is supplied then
the balance is set to 0.0

- the DEFAULT argument
  SAVINGS Declarations
class SAVINGS: public ACCOUNT{
protected:
   double drate;
public:
   SAVINGS(double bal=0.0,double pct=0.5);
   double compound();
   double withdraw(double amt);
};
  Definitions for SAVINGS
# include “accounts.h”
SAVINGS::SAVINGS(double bal,
                double pct):ACCOUNT(bal)
{
  drate = pct/100;
}
     Definitions Cont.

double SAVINGS::compound()
{
  double dinterest = rate * dbalance;
  dbalance += dinterest;
  return dinterest;
}
  More Declarations
class TIME_ACCT: public SAVINGS{
protected:
  double dfunds_avail;
public:
  TIME_ACCT( double bal = 0.0,
               double pct =0.5);
  double compound(); //redefinition
  double withdraw(double amt); //redefinition
  double get_avail() const {return dfunds_avail;}
Constructor defined

TIME_ACCT::TIME_ACCT(double bal,
         double pct):SAVINGS(bal,pct)
{
  dfunds_avail = 0.0;
}
 TIME_ACCT

double TIME_ACCT::compound()
{
   double dinterest = SAVINGS::compound();
   dfunds_avail += dinterest;
   return dinterest;
}//function keeps track of funds
MAIN POINTS

Constructors - calling the parent class can
lead to constructors being automatically
called at points higher in the hierarchy
eg TIME_ACCT - calls SAVINGS - calls
  ACCOUNT !
Functions can be overridden see the
  redefinitions
       TUTORIAL

• Complete the inheritance example covered in
  the lecture
• Additional if time permits - Create a function
  which can take two accounts as parameters:
  one a CHEQUE account and one a SAVINGS
  account and return the result of adding the
  balance from each account

				
DOCUMENT INFO