Inheritance
Chapter 9
1
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
Base Classes & Derived 5
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
Base Classes classes
Base Classes & Derived 7
Classes
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
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
Format
class :public
{
}; // 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
Note #define ACCOUNT_H
preprocessor CLASS BankAccount{
directives
public: void Deposit (float Dep);
int AccountNum( );
Note new float CurrentBalance ( );
category protected: int AccountNumber
protected:
float Balance;
};
#endif
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 ==> 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 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);
class
void CashCheck (float Amt);
protected: float Minimum;
float Charge; };
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.h”
class SuperNow : public Checking
Note: this class
{ public : SuperNow (int AcctNum = 0,
inherits all the
float Bal = 0,
protected
float Min = 5000.0,
variables from
float Chg = .5
Checking and
float Rate = 12.0);
BankAcct
void AddInterest( );
classes
protected :
float InterestRate; };
22
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);
protected:
float InterestRate; } ;
23
Class Family Hierarchy
BankAcct
Super_Now Savings
Checking
Deposit( ) Savings( )
Checking( ) Account_Num( ) Add_Interest( )
Cash_Check( ) Current_Balance( ) Withdraw( )
Minimum Account_Number Interest_rate
Charge Balance
Super_Now( )
Add_Interest( )
Interest_rate
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 ( 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
Overriding Base-Class 29
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
Public, Protected, Private 30
Inheritance
We will use mainly public inheritance
– can also have protected and private
inheritance
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
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
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
33
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
implementation)
34
Constructors & Destructors
Body of derived class destructor executed
Destructors for member objects (if any)
executed
Finally, base class’s destructor is
executed
Note: this is opposite sequence as for
constructors
Implicit Derived to Base- 35
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
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
functions
Solution will be to use virtual functions
and polymorphism in next chapter
Software Engineering with 38
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 class
But
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"
Case Study: Point, Circle, 43
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
Derived::Derived (int i, char c, double f)
: Base1 (i), Base2(c), real (f) { }