Inheritance - PowerPoint PPT Presentation

1 / 46
About This Presentation
Title:

Inheritance

Description:

Inheritance Chapter 9 What You Will Learn Software reusability (Recycling) Inheriting data members and functions from previously defined classes Introduction Software ... – PowerPoint PPT presentation

Number of Views:218
Avg rating:3.0/5.0
Slides: 47
Provided by: SArms5
Category:

less

Transcript and Presenter's Notes

Title: Inheritance


1
Inheritance
  • Chapter 9

2
What You Will Learn
  • Software reusability(Recycling)
  • Inheriting data members and functions from
    previously defined classes

3
Introduction
  • 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

4
Introduction
  • 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 classes
  • Derived class adds new data members and functions
  • Replace and refine existing members

5
Base Classes Derived Classes
  • 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)

6
Derived Classes -- Example
Derived classes
Base Classes
7
Base Classes Derived Classes
  • Inheritance produces tree like structures

- Checking Savings are derived from Bank
Account Class - Super-Now class derived from
Checking class
8
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

9
Declaring Derived Classes
  • Formatclass ltderived classgtpublic ltbase classgt
    ltDerived class member functionsgt
    ltDerived class member datagt // End class

10
Bank Account Class
  • Function Members
  • make a deposit
  • access account number
  • access account balance
  • Data members
  • account number
  • account balance

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

12
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

13
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)

14
Base Class Declared
ifndef ACCOUNT_H define ACCOUNT_H CLASS
BankAccount public void Deposit (float Dep)
int AccountNum( )
float CurrentBalance ( ) protected int
AccountNumber float
Balance endif
Note preprocessor directives
Note new category protected
15
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 gt abstract class

16
Base Class Declared
  • Protected Member
  • accessible to base class
  • accessible to any derived class
  • Thus accessible to any class within class family
  • NOT accessible to things outside the class family

17
Checking Class Declared
include account.h class Checkingpublic
BankAccount public Checking (int AcctNum
0000, float Bal
0, float Min
1000.,
float Chg .5) void CashCheck
(float Amt) protected float Minimum
float Charge
Note public base class allows all public
members of base class to be public in derived
class
18
Public Base Class
  • Designated as public in derived class declaration
  • 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

19
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 objects

20
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

21
Super-Now Derived Class
include checking.hclass SuperNow public
Checking public SuperNow (int AcctNum
0, float Bal 0,
float Min
5000.0, float Chg
.5 float Rate
12.0) void AddInterest( )
protected float InterestRate
Note this class inherits all the
protectedvariables from Checking and BankAcct
classes
22
Savings Derived Class
include account.hclass Savings public
BankAccount public Savings (int AcctNum
0, float Bal 0,
float Rate 12.0) void
AddInterest( ) void Withdraw (float Amt)
protected float InterestRate
Savings inherits all protected variables from
BankAcct
23
Class Family Hierarchy
BankAcct Deposit( )Account_Num(
)Current_Balance( )Account_NumberBalance
Super_Now Super_Now( )Add_Interest(
)Interest_rate
SavingsSavings( )Add_Interest( )Withdraw(
)Interest_rate
Checking Checking( ) Cash_Check(
) Minimum Charge
24
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

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

26
Casting Pointers
  • Consider an instance of a derived class
  • can be treated as an object of its base class
  • 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

27
Casting Pointers
  • Note Figure 9.4 -- casting base-class pointers
  • Use unary operator static_cast lt type gt (
    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

28
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

29
Overriding Base-Class Members
  • 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 CD

30
Public, Protected, Private Inheritance
  • We will use mainly public inheritance
  • can also have protected and private inheritance
  • Recall figure 9.4, line 49
  • Public and protected members of Point are
    inherited as public and protected members into
    Circle -- private members of base class are hidden

class Circle public Point // Circle inherits
from Point
31
Direct, Indirect Base Classes
  • 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

32
Constructors Destructors
  • Recall declaration of constructor of Circle
  • it in turn called the constructor of Point
  • Base constructor called implicitly first
  • Then derived class constructor executed
  • Finally, body of derived classs constructor is
    executed

CircleCircle (double r, int a, int b)
Point (a,b)
33
Constructors Destructors
  • If base class constructor requires parameters,
    these parameters must be passed by derived
    classs constructor
  • Note that our example with Checking and Super-Now
    did not operate this way(actually we didn't see
    the implementation)

34
Constructors Destructors
  • Body of derived class destructor executed
  • Destructors for member objects (if any) executed
  • Finally, base classs destructor is
    executedNote this is opposite sequence as for
    constructors

35
Implicit Derived to Base-Class Conversion
  • Under public inheritance, derived class-objects
    can be treated as base-class objects
  • 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

36
Mix Match base- and 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

37
Implicit Derived to Base-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 functions
  • Solution will be to use virtual functions and
    polymorphism in next chapter

38
Software Engineering with Inheritance
  • 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

39
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

40
Composition Vs. Inheritance
  • Changes to a derived class do not require
    recompiling of the base classBut
  • Changes in structure of Telephone_num for
    Employee, require recompilation of code which
    uses Telephone

41
"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 object

42
"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 object
  • Accomplished by pointer members linking one type
    of object to another
  • Sometimes called an "association"

43
Case Study Point, Circle, Cylinder
  • Author illustrates many points of the chapter
  • Refer to figure 9.8
  • Listen to audio explanation on Text CD

44
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

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

class Derived public Base1, public Base2 .
. .
46
Multiple Inheritance
  • Derived-class constructor calls each of
    base-class constructors
  • use member-initializer syntax
  • order is same as sequence of declaration

DerivedDerived (int i, char c, double f)
Base1 (i), Base2(c), real (f)
Write a Comment
User Comments (0)
About PowerShow.com