Inheritance by dffhrtcv3



  Chapter 9


What You Will Learn
   Software reusability

   Inheriting data members and functions
    from previously defined classes

 Software Reusability
   – saves time in program development
   – encourages use of proven, debugged code
   – reduces problems
 Write programs in general fashion
 Enables software designers to deal with
  complexity of modern software

 When creating a new class …
   – designate that class to inherit data
     members, functions of previously defined
     base class
   – result is a derived class
 Class can be derived from one or multiple
 Derived class adds new data members
  and functions
 Replace and refine existing members
Base Classes & Derived                    5

 Base classis more general
  – student, shape, loan
 Derived class is more specific
  – grad student, undergrad
  – circle, triangle, rectangle
  – carloan, home improvement, mortgage
 Some languages talk of
  – Superclass (base class)
  – Subclass (derived class)

Derived Classes -- Example

  Base Classes   classes
   Base Classes & Derived                                                7

      Inheritance produces tree like structures

         Banking Hierarchy

            Bank Account
                                      - Checking & Savings are derived
             Base Class
                                      from Bank Account Class
Checking Account
  Derived Class
                    Savings Account
                     Derived Class
                                      - Super-Now class derived from
                                      Checking class
Super-Now Account
  Derived Class

Design Tip

   Important link between derived class
    and base class
    – The “IS-A” relationship
   Examples
    – A checking account IS-A banking account
    – A savings account IS NOT a checking account
   If there is no IS-A relationship, do not
    use inheritance

Declaring Derived Classes

   Format
    class <derived class>:public <base class>
     { <Derived class member functions>
        <Derived class member data>
    }; // End class

Bank Account Class
 Function Members
   – make a deposit
   – access account number
   – access account balance
 Data members
   – account number
   – account balance

Checking Account Class
 Function Members
   – constructor to initialize data
   – cash a check (receive amt, debit balance)
 Data members
   – minimum balance, dictates per-check
   – per check charge amt

Super-Now Checking Class
 Function members
   – constructor to initialize Super-Now data
   – function to credit interest to account if
     balance above required minimum
 Data members
   – interest rate for balance above minimum

Savings Account Class
 Function Members
   – constructor
   – function to credit interest to account
   – function to debit account for withdrawal
 Data Members
   – annual interest rate (compounded monthly)

   Base Class Declared

               #ifndef ACCOUNT_H
Note           #define ACCOUNT_H
preprocessor   CLASS BankAccount{
               public: void Deposit (float Dep);
                        int AccountNum( );
Note new                float CurrentBalance ( );
category       protected: int AccountNumber
                            float Balance;

Base Class Declared
 Preprocessor statements
  – this header will be included in several
    additional files
 Note no constructor
  – properly used inheritance will not declare
    instances of base classes
  – no instances created ==> abstract class

Base Class Declared
 Protected Member
   – accessible to base class
   – accessible to any derived class
 Thus accessible to any class within class
 NOT accessible to things outside the class

  Checking Class Declared

                     #include “account.h”
                     class Checking:public BankAccount {
Note : public base
class allows all     public: Checking (int AcctNum = 0000,
public members of                      float Bal = 0,
base class to be                      float Min = 1000.,
public in derived                     float Chg = .5);
                             void CashCheck (float Amt);
                     protected:   float Minimum;
                                  float Charge; };

    Public Base Class

 Designated as public in derived class
 Inherited members of public base class
  maintain access level in derived class
    – inherited protected (or public) members remain
      protected (or public)
   Clients of derived class can invoke base class
    operations on derived class objects

Base Class not public

 Public members of the base class are not
  public members of the derived class
 Clients of the derived class cannot invoke
  base class operations on derived class

Protected vs. Public

   Protected
    – in base class declaration
    – allows access to protected members of base
      class by derived class
    – protected members accessible within class family
   Public
    – for declaring derived class
    – public members of the base class are public for
      derived class

  Super-Now Derived Class

                   #include “checking.h”
                   class SuperNow : public Checking
Note: this class
                   { public : SuperNow (int AcctNum = 0,
inherits all the
                                       float Bal = 0,
                                       float Min = 5000.0,
variables from
                                       float Chg = .5
Checking and
                                       float Rate = 12.0);
                               void AddInterest( );
                     protected :
                       float InterestRate; };

  Savings Derived Class

                       #include “account.h”
                       class Savings : public BankAccount
Savings inherits all   { public : Savings (int AcctNum = 0,
protected variables                  float Bal = 0,
from BankAcct                        float Rate = 12.0);
                           void AddInterest( );
                           void Withdraw (float Amt);
                          float InterestRate; } ;

 Class Family Hierarchy

Super_Now                                    Savings
                      Deposit( )           Savings( )
 Checking( )       Account_Num( )      Add_Interest( )
 Cash_Check( )    Current_Balance( )     Withdraw( )
 Minimum          Account_Number         Interest_rate
Charge                 Balance
Super_Now( )
Add_Interest( )

Protected Members
 Public members accessible by
  – all functions in the program
 Private members of base class accessible by
  – member functions
  – friends of the base class
 Protected members
  – intermediate level of protection
  – accessible by members, friends of base class
  – and by members, friends of derived classes

Protected Members
 Derived class members can refer to
   – public members
   – protected members of base class
   – simply use member names
 "Protected" items do away with
 Text recommends use of protected
  classification as last resort

Casting Pointers
 Consider an instance of a derived class
   – can be treated as an object of its base
 This means if we have an array of pointers
  to the base class, we could store pointers
  to objects of a variety of derived classes
 Reverse is not true …
   – a base class object is not also
     automatically a derived class object

Casting Pointers
 Note Figure 9.4 -- casting base-class
 Use unary operator
    static_cast < type > ( object)
   – Lines 88, 118, 127
 Review program description in text, on
  audio description of Text CD
 Note errors (garbage values) which can
  result from casting in the wrong direction

Using Member Functions
 If an object is private to the base class,
  compiler will forbid access by member of
  derived class -- this is encapsulation
 How will a derived class object access
  private data of base class?

                It will not!
 It won't -- directly anyway
 It must use available modifier functions
Overriding Base-Class                          29

 Inside a derived class you can have a new
  version of a function in the base class
 Which function is used (from derived
  class or base class) is determined by
  context -- by scope of the call
 Possible to call function in base class by
  use of scope operator ::
 Note figure 9.5, Overriding base class
  member function -- listen to audio on text
Public, Protected, Private                      30

 We will use mainly public inheritance
  – can also have protected and private
 Recall figure 9.4, line 49
     class Circle : public Point {
     // Circle inherits from Point

   Public and protected members of Point
    are inherited as public and protected
    members into Circle -- private members of
    base class are hidden
Direct, Indirect Base                            31

 Direct base class
   – one level above in hierarchy
   – specified in derived class's header with
     colon when declared
 Indirect base class
   – does not show up in the declaration
   – is two or more levels up in the hierarchy

 Constructors & Destructors
    Recall declaration of constructor of Circle
     – it in turn called the constructor of Point
Circle::Circle (double r, int a, int b)
      : Point (a,b)
  Base constructor called implicitly first
  Then derived class constructor executed
  Finally, body of derived class’s
   constructor is executed

Constructors & Destructors
   If base class constructor requires
    parameters, these parameters must be
    passed by derived class’s constructor

   Note that our example with Checking and
    Super-Now did not operate this way
    (actually we didn't see the

Constructors & Destructors
 Body of derived class destructor executed
 Destructors for member objects (if any)
 Finally, base class’s destructor is
  Note: this is opposite sequence as for
Implicit Derived to Base-                         35

Class Conversion
 Under public inheritance, derived class-
  objects can be treated as base-class
   – possible to assign checking object to bank
     account object
   – error: trying to access checking acct
     members from the bank acct object
 Cannot assign in the other direction
 However, can be made legit with properly
  designed overloaded = operator
Mix & Match base- and                         36

derived-class pointers
 Refer to base-class object w/base-class
  pointer … OK
 Refer to derived-class object w/derived-
  class pointer … OK
 Refer to derived-class obj w/base-class
  pointer … safe
   – checking account object is also a bank
     account object
   – can only reference base class members
 Refer to base-class obj w/derived-class
  pointer … ERROR
Implicit Derived to Base-                        37

Class Conversion
 May have array of base class pointers
   – can have them point to variety of derived
     class objects
 Problem : can access only base class
 Solution will be to use virtual functions
  and polymorphism in next chapter
Software Engineering with                    38

 Designers (or programmers of previous
  systems) provide base classes
 Client (or succeeding) programmer uses
  inheritance to make his/her version in a
  derived class
   – makes it specific for new application
   – source code of base class not needed,
     only .h and .obj files

Composition Vs. Inheritance
 Recall "is-a" relationship,
  – supported by public inheritance
  – savings acct object is a bank acct object
 Recall "has-a" relationship
  – hierarchical record structures
  – Bank-acct object has a telephone field or
    member, has a member number
  – This is an example of composition

Composition Vs. Inheritance
   Changes to a derived class do not require
    recompiling of the base class


   Changes in structure of Telephone_num
    for Employee, require recompilation of
    code which uses Telephone

"Uses A" Relationship
 Classes may not have the "is-a"
  relationship but they may need to "be
  aware" of each other
 Person object may use a Car object
 A function uses an object by issuing a
  function call to a member function of that

"Knows A" Relationship
 Example -- a Person object and a Car
  object cannot have an "is-a" relationship
  but ...
 The Person object may "know of" Car
 Accomplished by pointer members linking
  one type of object to another
 Sometimes called an "association"
Case Study: Point, Circle,                 43


 Author illustrates many points of the
 Refer to figure 9.8
 Listen to audio explanation on Text CD

Multiple Inheritance
   A class is derived from more than one
    base class
   Inherits members of several base classes
   Powerful tool but can cause some
    ambiguity problems
   Should be used when an "is-a"
    relationship exists between a new derived
    type and two or more existing base types
   Note figure 9.11 & audio description on
    Text CD

 Multiple Inheritance
    Indicate multiple inheritance by following
     colon : inheritance indicator with comma
     separated list of base classes

class Derived : public Base1, public Base2 {
   . . .

 Multiple Inheritance
    Derived-class constructor calls each of
     base-class constructors
      – use member-initializer syntax
      – order is same as sequence of declaration

Derived::Derived (int i, char c, double f)
  : Base1 (i), Base2(c), real (f) { }

To top