Title: C Programming: From Problem Analysis to Program Design, Second Edition
1C Programming From Problem Analysis to
Program Design, Second Edition
0
- Chapter 12 Inheritance and Composition
2Objectives
0
- In this chapter you will
- Learn about inheritance
- Learn about derived and base classes
- Explore how to redefine the member functions of a
base class - Examine how the constructors of base and derived
classes work - Learn how to construct the header file of a
derived class
3Objectives
0
- Become familiar with the C stream hierarchy
- Explore three types of inheritance public,
protected, and private - Learn about composition
- Become familiar with the three basic principles
of object-oriented design
4Inheritance and Composition
0
- The two common ways to relate two classes in a
meaningful way are - Inheritance (is-a relationship)
- Composition/Containment (has-a relationship)
5Inheritance
0
- Inheritance is an is-a relationship
- For instance,every employee is a person
- Inheritance lets us create new classes from
existing classes - New classes are called the derived classes
- Existing classes are called the base classes
- Derived classes inherit the properties of the
base classes
6Inheritance Hierarchy Among Vehicles
0
Every car is a wheeled vehicle.
7Inheritance
0
- is a mechanism by which one class acquires
(inherits) the properties (both data and
operations) of another class - the class being inherited from is the Base Class
(Superclass) - the class that inherits is the Derived Class
(Subclass) - the derived class is then specialized by adding
properties specific to it
8class TimeType Specification
0
- // SPECIFICATION FILE ( timetype.h )
- class TimeType
-
- public
- void Set ( int hours , int minutes ,
int seconds ) - void Increment ( )
- void Write ( ) const
- TimeType ( int initHrs, int initMins, int
initSecs ) // constructor - TimeType ( ) //
default constructor - private
- int hrs
- int mins
- int secs
8
9 0
Class Interface Diagram
TimeType class
Set
Private data hrs mins secs
Increment
Write
Time
Time
10Using Inheritance to Add Features
0
- ifndef EXTTIME //Always have file guard
- define EXTTIME
- // SPECIFICATION FILE ( exttime.h)
- include TimeType.h
- enum ZoneType EST, CST, MST, PST, EDT, CDT,
MDT, PDT - class ExtTime public TimeType
// Time is the base class -
- public
- void Set ( int hours, int minutes,
int seconds , -
ZoneType timeZone ) - void Write ( )
- ExtTime ( int initHrs , int initMins ,
int initSecs , - ZoneType initZone )
// constructor - ExtTime ( ) // default
constructor - private
- ZoneType zone // added data member
-
10
11class ExtTime public Time
0
- says class Time is a public base class of the
derived class ExtTime - as a result, all public members of Time (except
constructors) are also public members of ExtTime - in this example, new constructors are provided,
new data member zone is added, and member
functions Set and Write are overridden
12 Class Interface Diagram
0
ExtTime class
Set
Set
Private data hrs mins secs
Increment
Increment
Write
Write
Time
ExtTime
Time
ExtTime
Private data zone
13Client Code Using ExtTime
0
- include exttime.h // specification
file of ExtTime class - .
- .
- .
- ExtTime thisTime ( 8, 35, 0, PST )
- ExtTime thatTime // default
constructor called - thatTime.Write( ) // outputs
000000 EST - cout ltlt endl
- thatTime.Set (16, 49, 23, CDT)
- thatTime.Write( ) // outputs
164923 CDT - cout ltlt endl
- thisTime.Increment ( )
- thisTime.Increment ( )
- thisTime.Write ( ) // outputs
083502 PST - cout ltlt endl
-
13
14ExtTime Implementation File
0
- Constructors defined
- All added public member functions defined
- All changed base class public member function
defined - Destructor (if needed) defined
15Start of Implementation File
0
- // exttime.cpp implementation file
- // Put includes
- // needed by any of the member functions
- includeltstringgt // strings used
- includeltiostreamgt // IO used
- using namespace std
- // Always include class header file
- // DO NOT INCLUDE BASE CLASS HEADER
- include exttime.h
16Constructor Rules for Derived Classes
- at run time, the base class constructor is
implicitly called first, before the body of the
derived classs constructor executes - if the base class constructor requires
parameters, they must be passed by the derived
classs constructor
17Implementation of ExtTime Default Constructor
- ExtTime ExtTime ( )
- // Default Constructor Postcondition
- // hrs 0 mins 0 secs
0 - // (via an implicit call to base
class default constructor ) - // zone EST
-
- zone EST
18Implementation of Another ExtTime Class
Constructor
- ExtTime ExtTime ( / in / int
initHrs, - / in / int
initMins, - / in / int
initSecs, - / in /
ZoneType initZone ) - TimeType (initHrs, initMins,
initSecs) // constructor initializer - // Precondition 0 lt initHrs lt 23 0
lt initMins lt 59 - // 0 lt initSecs lt 59 initZone is
assigned - // Postcondition
- // zone initZone Time set by base class
constructor -
- zone initZone
18
19Implementation of ExtTimeSet function
- void ExtTime Set ( / in / int
hours, - / in / int
minutes, - / in / int
seconds, - / in /
ZoneType timeZone ) - // Precondition 0 lt hours lt 23 0 lt
minutes lt 59 - // 0 lt seconds lt 59 timeZone is
assigned - // Postcondition
- // zone timeZone Time set by base class
function -
- TimeType Set (hours, minutes,
seconds) - zone timeZone
19
20Implementation of ExtTimeWrite Function
- void ExtTime Write ( )
- // Postcondition
- // Time has been output in form HHMMSS ZZZ
- // where ZZZ is the time zone
abbreviation -
- static string zoneString8
-
- EST, CST, MST, PST, EDT,
CDT, MDT, PDT -
-
- TimeType Write ( )
- cout ltlt ltlt zoneString zone
-
20
21Inheritance (continued)
- Single inheritance derived class has a single
base class - Multiple inheritance derived class has more than
one base class - Can be viewed as a tree (hierarchy) where a base
class is shown with its derived classes - Public inheritance all public members of base
class are inherited as public members by derived
class
22(No Transcript)
23Inheritance (continued)
- Private members of the base class are private to
the base class - Members of the derived class cannot directly
access them - Public members of a base class can be inherited
either as public members or as private members by
the derived class - The derived class can include additional data
and/or function members
24Inheritance (continued)
- Derived class can redefine public member
functions of base class - Redefinition applies only to objects of the
derived class, not to the base class - All data/function members of the base class are
also data/function members of the derived class
(but can only be accessed via public member
functions of the base class)
25Redefining (Overriding) Member Functions of the
Base Class
- To redefine a public member function of a base
class - Corresponding function in the derived class must
have the same name, number, and types of
parameters
26Redefining (Overriding) Member Functions of the
Base Class (continued)
- If derived class overrides a public member
function of the base class, then to call the base
class function, specify - Name of the base class
- Scope resolution operator ()
- Function name with the appropriate parameter list
27Constructors of Derived and Base Classes
- Derived class constructor cannot directly access
private members of the base class - Derived class can initialize private data members
of the derived class - When a derived object is declared
- It must execute one of the base class
constructors - Call to the base class constructor is specified
in the heading of derived class constructor
definition
28Header File of a Derived Class
- To define new classes
- Create new header files
- To create new classes based on previously defined
classes - Header files of the new classes contain commands
that specify where to look for the definitions of
the base classes - The definitions of the member functions are
placed in a separate implementation file
29Class Files
- Each class (including derived classes used in
inheritance) has - Its own specification (header - .h) file to
define the class for users - Its own implementation file (.cpp) of public
member functions - For a derived class, its implementation file only
contains new public member functions or base
functions that are redefined
30Client Code Includes Class Definitions
- Use the preprocessor command (include) to
include a header file in a program for all
classes that you will use - If you use a derived class, you DO NOT have to
include its base header file (unless you are also
using its base class directly)
31Implementation File (.cpp) Compiles
- If you are the developer of a class, you also
compile its implementation file (.cpp) with your
program - If you are using a class developed by someone
else (string class, iostream class) they provide
the compiled code of its implementation file for
you (called an object module .o)
32Including Class Definitions
- Use the preprocessor command (include) to
include a header file in a program for all
classes that you will use - The preprocessor processes the program before it
is compiled and includes these files - To avoid multiple inclusion of a file in a
program - Use certain preprocessor commands in the header
file (file guard)
33Avoiding Multiple Inclusion of Header Files
- often several program files use the same header
file containing typedef statements, constants, or
class type declarations--but, it is a
compile-time error to define the same identifier
twice - this preprocessor directive syntax is used to
avoid the compilation error that would otherwise
occur from multiple uses of include for the same
header file - ifndef Preprocessor_Identifier
- define Preprocessor_Identifier
- .
- .
- .
- endif
34Example Using Preprocessor Directive ifndef
- // timetype .h FOR COMPILATION THE CLASS
DECLARATION IN - // SPECIFICATION FILE FILE timetype.h WILL BE
INCLUDED ONLY ONCE - ifndef TIME_H // Make this a
different name than the class - define TIME_H // case sensitive -
you can uppercase the class name -
- class TimeType
-
- public
- . . .
-
- private
- . . .
-
- endif
35Using File Guards Are Required
- For user developed classes (like your own) that
are not derived classes, no one else will be
using them, and you can get away with not using
these file guards - For inherited classes, you will get errors if you
do not use file guards - FROM NOW ON YOU ARE REQUIRED TO USE THEM FOR ALL
YOUR HEADER FILES
36Inheritance ExampleC Stream Classes
0
- ios is the base class for all stream classes
- istream and ostream are derived from ios
- ifstream is derived from istream
- ofstream is derived from the ostream
- ios contains formatting flags and member
functions to access/modify the flag settings
370
38C Stream Classes (continued)
0
- istream and ostream provide operations for data
transfer between memory and devices - istream defines the extraction operator (gtgt) and
functions such as get and ignore - ostream defines the insertion operator (ltlt),
which is used by cout
39C Stream Classes (continued)
0
- ifstream is derived from istream for file input
- ofstream is derived from ostream for file output
- Objects of type ifstream are for file input
- Objects of type ofstream are for file output
- Header file fstream contains the definitions of
ifstream and ofstream
40Protected Members of a Class
0
- Private members of a class cannot be directly
accessed outside the class - For a base class to give derived class access to
a private member - Declare that member as protected
- The accessibility of a protected member of a
class is in between public and private - A derived class can directly access the protected
member of the base class
41Public Inheritance
0
- If the memberAccessSpecifier is public, then
- Public members of A (base) are public members of
B (derived) and can be directly accessed in class
B - Protected members of A are protected members of B
and can be directly accessed by the member
functions of B - Private members of A are hidden in B and can be
accessed by member functions of B through public
or protected members of A
42Protected Inheritance
0
- If the memberAccessSpecifier is protected, then
- Public members of A are protected members of B
and can be accessed by the member functions of B - Protected members of A are protected members of B
and can be accessed by the member functions of B - Private members of A are hidden in B and can be
accessed by member functions of B through public
or protected members of A
43Private Inheritance
0
- If the memberAccessSpecifier is private, then
- Public members of A are private members of B and
can be accessed by member functions of B - Protected members of A are private members of B
and can be accessed by member functions of B - Private members of A are hidden in B and can be
accessed by member functions of B through the
public or protected members of A
44Public Private - Protected
0
- Access to items of the base class
- Client Derived
class - Public Yes Yes
- Private No No
- Protected No Yes
- No Can only access via public member functions
45Why Use Inheritance?
0
- Inheritance is used quite frequently
- It saves coding you only have to add or redefine
the public member functions unique for your class - It helps organize and simplify large programs
- The client doesnt have to know anything about
the hierarchy just uses the derived class
46Composition (or Containment)
0
- is a mechanism by which an object of one class
contains an object of another class - Called a has-a relationship
47A TimeCard object has a Time object
0
- include TimeType.h
- class TimeCard
-
- public
- void Punch ( / in / int hours,
- / in / int
minutes, - / in /
int seconds ) - void Print ( )
- TimeCard ( / in / int idNum,
- / in / int initHrs,
- / in / int initMins,
- / in / int
initSecs ) - TimeCard ( )
- private
- long id
- TimeType timeStamp
-
48 0
TimeCard Class
TimeCard has a TimeType object
Private data id timeStamp
Print . . .
Private data hrs mins secs
Set
Increment
Write . . .
TimeCard
TimeCard
49TimeCard Constructor
0
- TimeCard TimeCard ( / in / int idNum,
- / in / int initHrs,
- / in / int initMins,
- / in
/ int initSecs ) - timeStamp (initHrs, initMins, initSecs)
// constructor initializer - // Precondition 0 lt initHrs lt 23 0
lt initMins lt 59 - // 0 lt initSecs lt 59 initNum is
assigned - // Postcondition
- // id idNum timeStamp set by its
constructor -
- id idNum
49
50Default Constructor
0
- TimeCard TimeCard ( )
- // Default constructor
- // timeStamp default constructor is called
-
- id 0
51Punch Print Member Functions
0
- void TimeCardPunch (int hrs, int min, int sec)
-
- timeStamp.Set(hrs, min, sec)
-
- void TimeCardPrint()
-
- cout ltlt "For ID " ltlt id ltlt endl
- cout ltlt "Timestamp is "
- timeStamp.Write()
- cout ltlt endl
52Sample Client Code
0
- cout ltlt "Enter employee 1 ID "
- cin gtgt empID1
- cout ltlt endl
- TimeCard timeCard1(empID1, 8, 1, 2)
- TimeCard timeCard2
- timeCard1.Print()
- timeCard2.Print()
- timeCard2.Punch(9,3,4)
- timeCard2.Print()
53Order in Which Constructors are Executed
0
- Given a class X,
- if X is a derived class its base class
constructor is executed first - next, constructors for member objects (if any)
are executed (using their own default
constructors if none is specified) - finally, the body of Xs constructor is executed
54Two Programming Paradigms
0
Structural (Procedural) Object-Oriented
PROGRAM (C) PROGRAM (C)
55What is an object?
0
OBJECT
set of methods (public member functions) interna
l state (values of private data members)
Operations Data
56OOD and OOP
0
- The fundamental principles of Object-Oriented
Design (OOD) are - Encapsulation combine data and operations on
data in a single unit - Inheritance create new objects from existing
objects - Polymorphism the ability to use the same
expression to denote different operations
57OOD and OOP (continued)
0
- OOD
- Object is a fundamental entity
- Debug objects
- Program is a collection of interacting objects
- Programmer is object-oriented
- OOD encourages code reuse
58OOD and OOP (continued)
- Structured programming
- Function is a fundamental entity
- Debug functions
- Program is a collection of interacting functions
- Programmer is action-oriented
59OOD and OOP (continued)
- Object-oriented programming (OOP) implements OOD
- C supports OOP through the use of classes
- Polymorphic function or operator has many forms
- Function name and operators can be overloaded
60OOD and OOP (continued)
- Every object has an internal state and an
external interface - Private data form the internal state
- Public member functions are the external
interface - Only the object can manipulate its internal state
61Classes, Objects, Operations
- Finding classes begin with a problem description
and identify all nouns and verbs - From the list of nouns choose the classes
- From the list of verbs choose the operations
(public member functions) - Suppose we want to write a program that
calculates and prints the volume and surface area
of a cylinder
62Classes, Objects, Operations (continued)
- We can state this problem as follows
- Write a program to input the dimensions of a
cylinder and calculate and print the surface area
and volume - The nouns are bold and the verbs are italic
- From the list of nouns we visualize a cylinder as
a class (cylinderType) from which we can create
many cylinder objects of various dimensions
63Classes, Objects, Operations (continued)
- The nouns (dimensions, surface area, and volume)
are characteristics of a cylinder - After identifying a class, determine three pieces
of information about its objects - Operations that an object can perform
- Operations that can be performed on an object
- Information that an object must maintain
64Classes, Objects, Operations (continued)
- From the verbs, choose a list of possible
operations that an object of that class can
perform, or have performed, on itself - For the cylinderType class the possible
operations are - Input, calculate, and print
- Dimensions represent the data
65Classes, Objects, Operations (continued)
- The center of the base, radius of the base, and
height of the cylinder are the characteristics of
the dimensions - Calculate determine the volume and the surface
area - You can deduce the operations cylinderVolume and
cylinderSurfaceArea - Print display the volume and the surface area on
an output device
66Classes, Objects, Operations (continued)
- Identifying classes via the nouns and verbs from
the descriptions to the problem is not the only
technique possible - There are several other OOD techniques in the
literature
67Programming Example
- This programming example illustrates the concepts
of inheritance and composition - Problem The mid-semester point at your local
university is approaching - The registrars office wants to prepare the grade
reports as soon as the students grades are
recorded
68Programming Example (continued)
- Some of the students enrolled have not yet paid
their tuition - If a student has paid the tuition, the grades are
shown on the grade report together with the
grade-point average (GPA) - If a student has not paid the tuition, the grades
are not printed - Grade report indicates that grades have been held
for nonpayment of the tuition - Grade report also shows the billing amount
69The Data File
- Data are stored in a file in the following form
- 15000 345
- studentName studentID isTuitionPaid
numberOfCourses - courseName courseNumber creditHours grade
- courseName courseNumber creditHours grade
- .
- studentName studentID isTuitionPaid
numberOfCourses - courseName courseNumber creditHours grade
- courseName courseNumber creditHours grade
- .
70The Data File (continued)
- The first line indicates number of students
enrolled and tuition rate per credit hour - Students data is given thereafter
- A sample-input file is
- 3 345
- Lisa Miller 890238 Y 4
- Mathematics MTH345 4 A
- Physics PHY357 3 B
- ComputerSci CSC478 3 B
- History HIS356 3 A
- .
71Output
- Sample output for each student
- Student Name Lisa Miller
- Student ID 890238
- Number of courses enrolled 4
- Course No Course Name Credits Grade
- CSC478 ComputerSci 3 B
- HIS356 History 3 A
- MTH345 Mathematics 4 A
- PHY357 Physics 3 B
- Total number of credits 13
- Mid-Semester GPA 3.54
72Input and Output
- Input file containing data in the form given
above - Assume that the name of the input file is
"stData.txt" - Output a file containing output of the form
given above
73Problem Analysis
- Two main components are
- Course
- Main characteristics of a course are course
name, course number, and number of credit hours - Student
- Main characteristics of a student are student
name, student ID, number of courses enrolled,
name courses, and grade for each course
74Problem Analysis (continued)
- Operations on an object of the course type are
- Set the course information
- Print the course information
- Show the credit hours
- Show the course number
75(No Transcript)
76Algorithm Design
- The basic operations to be performed on an object
of the type studentType - Set student information
- Print student information
- Calculate number of credit hours taken
- Calculate GPA
- Calculate billing amount
- Sort courses according to course number
77(No Transcript)
78Main Program
- Declare variables
- Open input file
- If input file does not exist, exit program
- Open output file
- Get number of students registered and tuition
rate - Load students data
- Print grade reports
79Summary
- Inheritance and composition are meaningful ways
to relate two or more classes - Inheritance is an is-a relation
- Composition is a has-a relation
- Single inheritance a derived class is derived
from one class, called the base class - Multiple inheritance a derived class is derived
from more than one base class
80Summary
- Private members of a base class are private to
the base class - Public members of a base class can be inherited
either as public or private - Derived class can redefine function members of a
base class - Redefinition applies only to objects of derived
class
81Summary
- A call to a base class constructor (with
parameters) is specified in the heading of the
definition of the derived class constructor - When initializing object of a derived class, the
base class constructor is executed first - In composition
- Class member is an object of another class
- Call to constructor of member objects is
specified in heading of the definition of classs
constructor
82Summary
- Three basic principles of OOD are
- Encapsulation
- Inheritance
- Polymorphism
- Finding classes describe the problem and choose
classes from the list of nouns and operations
from the list of verbs