Title: INHERITANCE AND COMPOSITION
1Chapter 14
- INHERITANCE AND COMPOSITION
2Objectives
- 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
- 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
- The two common ways to relate two classes in a
meaningful way are - 1. Inheritance (is-a relationship)
- 2. Composition (has-a relationship)
5Inheritance
- Design a class, partTimeEmployee, to implement
and process the characteristics of a part-time
employee - Every part-time employee has a name, pay rate,
and number of hours worked - Every part-time employee is a person
- Rather than design the class partTimeEmployee
from scratch, we want to be able to extend the
definition of the class personType by adding
additional members (data and/or function)
6Inheritance
- We do not want to make the necessary changes
directly to the class personTypethat is, edit
the class personType, and add and/or delete
members - We want to create the class partTimeEmployee
without making any physical changes to the class
personType, by adding only the members that are
necessary - The new class that we create from existing
classes is called the derived class and the
existing classes are called the base classes
7Inheritance
- Single inheritance- the derived class is derived
from a single base class - Multiple inheritance- the derived class is
derived from more than one base class - Inheritance can be viewed as a tree-like, or
hierarchical, structure wherein a base class is
shown with its derived classes - The word public in a heading, called the member
access specifier, specifies that all public
members of the class shape are inherited as
public members by the class circle
8Inheritance
9Facts
- The following facts about the base and the
derived classes should be kept in mind - 1. The private members of the base class are
private to the base class hence, the members of
the derived class cannot directly access them - 2. The public members of a base class can be
inherited either as public members or as private
members by the derived class - 3. The derived class can include additional data
and/or function members
10Facts
- 4. The derived class can redefine the public
member functions of the base class. However, this
redefinition applies only to the objects of the
derived class, not to the objects of the base
class - 5. All data members of the base class are also
data members of the derived class. Similarly, the
member functions of the base class (unless
redefined) are also the member functions of the
derived class
11Constructors
- A derived class can have its own private data
members - Member functions of the derived class cannot
directly access the private members of the base
class - The constructors of the derived class can
(directly) initialize only the private data
members of the derived class - When a derived class object is declared, it must
also automatically execute one of the
constructors of the base class
12Constructors
- The execution of a derived classs constructor
must trigger the execution of one of the base
classs constructors - A call to the base classs constructor is
specified in the heading part of the derived
class constructors definition
13Multiple Inclusions
- Suppose that the header file testA.h includes the
file test.h to make use of the identifiers one
and two - The preprocessor first includes the header file
test.h and then the header file testA.h - When the header file testA.h is included, because
it contains the preprocessor directive include
"test.h", the header file test.h will be included
twice in the program - The second inclusion of the header file test.h
will result in compile-time errors, such as
identifier one already being declared - To avoid multiple inclusion of a file in a
program we use certain preprocessor commands in
the header file
14Stream Classes
15Stream Classes
- The class ios is the base class for all stream
classes - Classes istream and ostream are directly derived
from the class ios - The class ifstream is derived from the class
istream, and the class ofstream is derived from
the class ostream - The class ios contains formatting flags and
member functions to access and/or modify the
setting of these flags
16Stream Classes
- To identify the I/O status, the class ios
contains an integer status word - This integer status word provides a continuous
update reporting the status of the stream - The classes istream and ostream are responsible
for providing the operations for the data
transfer between memory and devices
17Stream Classes
- The class istream defines the extraction
operator, gtgt, and functions such as get and
ignore - The class ostream defines the insertion operator,
ltlt, which is used by the object cout - The class ifstream is derived from the class
istream to provide the file input operations - The class ofstream is derived from the class
ostream to provide the file output operations
18Stream Classes
- Objects of the type ifstream are used for file
input - Objects of the type ofstream are used for file
output - The header file fstream contains the definition
of the classes ifstream and ofstream
19Protected Members of a Class
- The private members of a class are private to the
class and cannot be directly accessed outside the
class - The derived class cannot access private members
of a class - It is sometimes necessary for a derived class to
access a private member of a base class - If you make a private member become public, then
anyone can access that member
20Protected Members of a Class
- For a base class to give access to a private
member to its derived class and still prevent its
direct access outside the class, you must declare
that member under the memberAccessSpecifier
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 a base class
21Inheritance
- 1. If memberAccessSpecifier is public, then
- a. The public members of A are public members of
B and they can be directly accessed in class B - b. The protected members of A are protected
members of B and they can be directly accessed by
the member functions (and friend functions) of B - c. The private members of A are hidden in B and
they can be accessed by the member functions (and
friend functions) of B through the public or
protected members of A
22Inheritance
- 2. If memberAccessSpecifier is protected, then
- a. The public members of A are protected members
of B and they can be accessed by the member
functions (and friend functions) of B - b. The protected members of A are protected
members of B and they can be accessed by the
member functions (and friend functions) of B - c. The private members of A are hidden in B and
they can be accessed by the member functions (and
friend functions) of B through the public or
protected members of A
23Inheritance
- 3. If memberAccessSpecifier is private, then
- a. The public members of A are private members of
B and they can be accessed by the member
functions (and friend functions) of B - b. The protected members of A are private members
of B and they can be accessed by the member
functions (and friend functions) of B - c. The private members of A are hidden in B and
they can be accessed by the member functions (and
friend functions) of B through the public or
protected members of A
24Composition
- In composition one or more member(s) of a class
is an object of another class type - Composition is a has-a relation
- The arguments to the constructor of a
member-object are specified in the heading part
of the definition of the constructor of the class - Member-objects of a class are constructed in the
order they are declared, not in the order they
are listed in the constructors member
initialization list, and before the enclosing
class objects are constructed
25OOD and OOP
- The fundamentals of Object-Oriented Design (OOD)
are - 1. Encapsulationcombine data and operations on
data in a single unit - 2. Inheritancecreate new objects from existing
objects - 3. Polymorphismthe ability to use the same
expression to denote different operations - In OOD an object is a fundamental entity, while
in structured programming a function is a
fundamental entity
26OOD and OOP
- In OOD we debug objects, while in structured
programming we debug functions - In structured programming a program is a
collection of interacting functions, while in OOD
a program is a collection of interacting objects - OOD encourages code reuse
- In structured programming the programmer is
action-oriented, while in OOD the programmer is
object-oriented
27OOD and OOP
- Object-oriented programming (OOP) implements OOD
- C supports OOP through the use of classes
- A polymorphic function or operator has many forms
- A function name and operators can be overloaded
- Templates provide parametric polymorphism
- C provides virtual functions as a means to
implement polymorphism in an inheritance hierarchy
28OOD and OOP
- Objects are created when class variables are
declared - Objects interact with each other via function
calls - Every object has an internal state and external
state - The private members form the internal state and
the public members form the external state - Only the object can manipulate its internal state
29Classes, Objects, Operations
- We begin with a description of the problem and
then identify all of the nouns and verbs - From the list of nouns we choose our classes, and
from the list of verbs we choose our operations - Suppose that we want to write a program that
calculates and prints the volume and surface area
of a cylinder
30Classes, Objects, Operations
- 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 nounsprogram, dimensions,
cylinder, surface area, and volumewe can easily
visualize cylinder to be a classsay,
cylinderTypefrom which we can create many
cylinder objects of various dimensions
31Classes, Objects, Operations
- The nounsdimensions, surface area, and
volumeare characteristics of a cylinder - After we identify a class, the next step is to
determine three pieces of information - Operations that an object of that class type can
perform - Operations that can be performed on an object of
that class type - Information that an object of that class type
must maintain
32Classes, Objects, Operations
- From the list of verbs identified in the problem
description, choose a list of possible operations
that an object of that class can perform, or has
performed, on itself - From the list of verbs for the cylinder problem
descriptionwrite, input, calculate, and
printthe possible operations for a cylinder
object are input, calculate, and print - For the cylinderType class, the dimensions
represent the data
33Classes, Objects, Operations
- The center of the base, radius of the base, and
height of the cylinder are the characteristics of
the dimensions - The verb calculate applies to determining the
volume and the surface area - You can deduce the operations cylinderVolume and
cylinderSurfaceArea - The verb print applies to the display of the
volume and the surface area on an output device
34Classes, Objects, Operations
- 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
literature
35Programming Example
- This programming example further illustrates the
concepts of inheritance and composition - 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
36Programming Example
- Some of the students enrolled have not yet paid
their tuition, however, - 1. If a student has paid the tuition, the grades
are shown on the grade report together with the
grade-point average (GPA) - 2. If a student has not paid the tuition, the
grades are not printed - For these students, the grade report contains a
message indicating that the grades have been held
for nonpayment of the tuition - The grade report also shows the billing amount
37The Data File
- The 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
- .
38The Data File
- The first line indicates the number of students
enrolled and the tuition rate per credit hour - The 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
- .
39Output
- The desired output for each student is of the
form - 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
40Input and Output
- Input - a file containing data in the form given
above - For easy reference in the rest of the discussion,
we assume that the name of the input file is
"astData.txt" - Output - a file containing output of the form
given above
41Problem Analysis
- The two main components that we see are student
and course - Course
- the main characteristics of a course are the
course name, course number, and number of credit
hours - although the grade a student receives is not
really a characteristic of a course, to simplify
the program this component also includes the
students grade
42Problem Analysis
- Operations on an object of the course type are
- 1. Set the course information
- 2. Print the course information
- 3. Show the credit hours
- 4. Show the course number
- 5. Show the grade
- Student
- The main characteristics of a student are the
student name, student ID, number of courses in
which enrolled, courses in which enrolled, and
grade for each course
43Problem Analysis
- Because every student has to pay tuition, we also
include a member to indicate whether the student
has paid the tuition - Every student is a person, and every student
takes courses - We have already designed a class personType to
process a persons first name and last name - We can derive the class studentType to keep track
of a students information from the class
personType, and one member of this class is of
the type courseType
44Algorithm Design
- The basic operations to be performed on an object
of the type studentType are as follows - 1. Set the student information
- 2. Print the student information
- 3. Calculate the number of credit hours taken
- 4. Calculate the GPA
- 5. Calculate the billing amount
- 6. Because the grade report will print the
courses in ascending order, sort the courses
according to the course number
45Main Program
- 1. Declare the variables
- 2. Open the input file
- 3. If the input file does not exist, exit the
program - 4. Open the output file
- 5. Get the number of students registered and the
tuition rate - 6. Load the students data
- 7. Print the grade reports
46Variables
- studentType studentListmaxNumberOfStudents
- //array to store the students data
- int noOfStudents //variable to store the
//number of students - double tuitionRate //variable to store the
tuition rate - ifstream infile //input stream variable
- ofstream outfile //output stream variable