Title: Inheritance
1Inheritance
2What You Will Learn
- Software reusability(Recycling)
- Inheriting data members and functions from
previously defined classes
3Introduction
- 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
4Introduction
- 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
5Base 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)
6Derived Classes -- Example
Derived classes
Base Classes
7Base Classes Derived Classes
- Inheritance produces tree like structures
- Checking Savings are derived from Bank
Account Class - Super-Now class derived from
Checking class
8Design 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
9Declaring Derived Classes
- Formatclass ltderived classgtpublic ltbase classgt
ltDerived class member functionsgt
ltDerived class member datagt // End class
10Bank Account Class
- Function Members
- make a deposit
- access account number
- access account balance
- Data members
- account number
- account balance
11Checking 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
12Super-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
13Savings Account Class
- Function Members
- constructor
- function to credit interest to account
- function to debit account for withdrawal
- Data Members
- annual interest rate (compounded monthly)
14Base 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
15Base 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
16Base 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
17Checking 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
18Public 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
19Base 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
20Protected 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
21Super-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
22Savings 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
23Class 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
24Protected 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
25Protected 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
26Casting 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
27Casting 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
28Using 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
29Overriding 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
30Public, 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
31Direct, 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
32Constructors 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)
33Constructors 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)
34Constructors 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
35Implicit 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
36Mix 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
37Implicit 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
38Software 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
39Composition 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
40Composition 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"
43Case Study Point, Circle, Cylinder
- Author illustrates many points of the chapter
- Refer to figure 9.8
- Listen to audio explanation on Text CD
44Multiple 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
45Multiple Inheritance
- Indicate multiple inheritance by following colon
inheritance indicator with comma separated list
of base classes
class Derived public Base1, public Base2 .
. .
46Multiple 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)