c++ programming: from problem analysis to program design, second edition chapter 12: inheritance and...

82
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

Upload: claud-ross

Post on 13-Dec-2015

221 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysisto Program Design, Second Edition

Chapter 12: Inheritance and Composition

Page 2: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 2

Objectives

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

Page 3: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 3

Objectives

• 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

Page 4: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 4

Inheritance and Composition

• The two common ways to relate two classes in a meaningful way are:

1. Inheritance (“is-a” relationship)

2. Composition/Containment (“has-a” relationship)

Page 5: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 5

Inheritance

• 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

Page 6: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 6

Inheritance Hierarchy Among Vehicles

vehicle

wheeled vehicle boat

bicyclecar

four-door two-door

Every car is a wheeled vehicle.

Page 7: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 7

Inheritance

• 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

Page 8: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 8

class TimeType Specification// 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

Page 9: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 9

Class Interface Diagram

Private data:

hrs

mins

secs

Set

Increment

Write

Time

Time

TimeType class

Page 10: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 10

Using Inheritance to Add Features #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

} ;#endif // End of file: end file guard preprocessor if statement

10

Page 11: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 11

class ExtTime: public Time

• 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

Page 12: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 12

Class Interface Diagram

Private data:

hrs

mins

secs

ExtTime class

Set

Increment

Write

Time

Time

Set

Increment

Write

ExtTime

ExtTime

Private data:zone

Page 13: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 13

Client Code Using ExtTime

#include “exttime.h” // specification file of ExtTime class . . .

ExtTime thisTime ( 8, 35, 0, PST ) ; ExtTime thatTime ; // default constructor called

thatTime.Write( ) ; // outputs 00:00:00 EST cout << endl ;

thatTime.Set (16, 49, 23, CDT) ; thatTime.Write( ) ; // outputs 16:49:23 CDT

cout << endl ;

thisTime.Increment ( ) ; thisTime.Increment ( ) ; thisTime.Write ( ) ; // outputs 08:35:02 PST cout << endl ; 13

Page 14: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 14

ExtTime Implementation File

• Constructors defined• All added public member functions defined• All changed base class public member

function defined• Destructor (if needed) defined

Page 15: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 15

Start of Implementation File

// exttime.cpp implementation file// Put includes// needed by any of the member functions#include<string> // strings used#include<iostream> // IO usedusing namespace std;// Always include class header file // DO NOT INCLUDE BASE CLASS HEADER#include “exttime.h”

Page 16: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 16

Constructor Rules for Derived Classes

• at run time, the base class constructor is implicitly called first, before the body of the derived class’s constructor executes

• if the base class constructor requires parameters, they must be passed by the derived class’s constructor

Page 17: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 17

Implementation 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 ;

}

Page 18: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 18

Implementation 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 <= initHrs <= 23 && 0 <= initMins <= 59

// 0 <= initSecs <= 59 && initZone is assigned

// Postcondition:

// zone == initZone && Time set by base class constructor

{

zone = initZone ;

}

18

Page 19: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 19

Implementation of ExtTime::Set function void ExtTime :: Set ( /* in */ int hours,

/* in */ int minutes,

/* in */ int seconds,

/* in */ ZoneType timeZone )

// Precondition: 0 <= hours <= 23 && 0 <= minutes <= 59

// 0 <= seconds <= 59 && timeZone is assigned

// Postcondition:

// zone == timeZone && Time set by base class function

{

TimeType :: Set (hours, minutes, seconds);

zone = timeZone ;

}

19

Page 20: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 20

Implementation of ExtTime::Write Function

void ExtTime :: Write ( )

// Postcondition:// Time has been output in form HH:MM:SS ZZZ// where ZZZ is the time zone abbreviation{ static string zoneString[8] = { “EST”, CST”, MST”, “PST”, “EDT”, “CDT”, “MDT”, “PDT” } ; TimeType :: Write ( ) ; cout << ‘ ‘ << zoneString [zone] ;}

20

Page 21: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 21

Inheritance (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

Page 22: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition
Page 23: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 23

Inheritance (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

Page 24: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 24

Inheritance (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)

Page 25: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 25

Redefining (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

Page 26: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 26

Redefining (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

Page 27: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 27

Constructors 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

Page 28: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 28

Header 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

Page 29: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 29

Class 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

Page 30: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 30

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

Page 31: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 31

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

Page 32: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 32

Including 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”)

Page 33: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 33

• 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

Avoiding Multiple Inclusion of Header Files

Page 34: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 34

Example 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

Page 35: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 35

Using 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

Page 36: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 36

Inheritance Example:C++ Stream Classes

• 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

Page 37: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition
Page 38: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 38

C++ Stream Classes (continued)

• istream and ostream provide operations for data transfer between memory and devices

• istream defines the extraction operator (>>) and functions such as get and ignore

• ostream defines the insertion operator (<<), which is used by cout

Page 39: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 39

C++ Stream Classes (continued)

• 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

Page 40: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 40

Protected Members of a Class

• 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

Page 41: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 41

Public Inheritance

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

Page 42: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 42

Protected Inheritance

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

Page 43: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 43

Private Inheritance

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

Page 44: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 44

Public – Private - Protected

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

Page 45: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 45

Why Use Inheritance?

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 doesn’t have to know anything about the hierarchy – just uses the derived class

Page 46: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 46

Composition (or Containment)

• is a mechanism by which an object of one class contains an object of another class

• Called a “has-a” relationship

Page 47: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 47

A TimeCard object has a Time object #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 ; } ;

Page 48: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 48

TimeCard ClassTimeCard has a TimeType object

Private data:

hrs

mins

secs

Punch

Private data:

id

timeStamp

Increment

SetPrint . . .

TimeCard

TimeCard

Write . . .

Page 49: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 49

TimeCard Constructor TimeCard :: TimeCard ( /* in */ int idNum,

/* in */ int initHrs,

/* in */ int initMins,

/* in */ int initSecs )

: timeStamp (initHrs, initMins, initSecs) // constructor initializer

// Precondition: 0 <= initHrs <= 23 && 0 <= initMins <= 59

// 0 <= initSecs <= 59 && initNum is assigned

// Postcondition:

// id == idNum && timeStamp set by its constructor

{

id = idNum ;

}

49

Page 50: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 50

Default Constructor

TimeCard :: TimeCard ( )

// Default constructor:

// timeStamp default constructor is called

{

id = 0;

}

Page 51: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 51

Punch Print Member Functions

void TimeCard::Punch (int hrs, int min, int sec){ timeStamp.Set(hrs, min, sec);}void TimeCard::Print(){ cout << "For ID: " << id << endl; cout << "Timestamp is: "; timeStamp.Write(); cout << endl;}

Page 52: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 52

Sample Client Code

cout << "Enter employee 1 ID: "; cin >> empID1; cout << endl; TimeCard timeCard1(empID1, 8, 1, 2); TimeCard timeCard2; timeCard1.Print(); timeCard2.Print(); timeCard2.Punch(9,3,4); timeCard2.Print();

Page 53: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 53

Order in Which Constructors are Executed

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 X’s constructor is executed

Page 54: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 54

Two Programming Paradigms

Structural (Procedural) Object-Oriented PROGRAM (C) PROGRAM (C++)

FUNCTION

FUNCTION

FUNCTION

OBJECT

Operations

Data

OBJECT

Operations

Data

OBJECT

Operations

Data

Page 55: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 55

What is an object?

OBJECT

Operations

Data

set of methods(public member functions)

internal state(values of private data members)

Page 56: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 56

OOD and OOP

• 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

Page 57: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 57

OOD and OOP (continued)

• OOD

− Object is a fundamental entity

− Debug objects

− Program is a collection of interacting objects

− Programmer is object-oriented

− OOD encourages code reuse

Page 58: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 58

OOD and OOP (continued)

• Structured programming

− Function is a fundamental entity

− Debug functions

− Program is a collection of interacting functions

− Programmer is action-oriented

Page 59: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 59

OOD 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

Page 60: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 60

OOD 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

Page 61: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 61

Classes, 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

Page 62: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 62

Classes, 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

Page 63: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 63

Classes, 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

Page 64: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 64

Classes, 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

Page 65: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 65

Classes, 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

Page 66: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 66

Classes, 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

Page 67: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 67

Programming Example

• This programming example illustrates the concepts of inheritance and composition

• Problem: The mid-semester point at your local university is approaching

− The registrar’s office wants to prepare the grade reports as soon as the students’ grades are recorded

Page 68: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 68

Programming 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

Page 69: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 69

The Data File

• Data are stored in a file in the following form: 15000 345studentName studentID isTuitionPaid numberOfCoursescourseName courseNumber creditHours gradecourseName courseNumber creditHours grade.studentName studentID isTuitionPaid numberOfCoursescourseName courseNumber creditHours gradecourseName courseNumber creditHours grade.

Page 70: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 70

The 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

.

Page 71: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 71

Output

• Sample output for each student:Student Name: Lisa MillerStudent ID: 890238Number of courses enrolled: 4Course No Course Name Credits Grade CSC478 ComputerSci 3 BHIS356 History 3 AMTH345 Mathematics 4 APHY357 Physics 3 BTotal number of credits: 13Mid-Semester GPA: 3.54

Page 72: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 72

Input 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

Page 73: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 73

Problem 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

Page 74: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 74

Problem Analysis (continued)

− 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

Page 75: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition
Page 76: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 76

Algorithm Design

• The basic operations to be performed on an object of the type studentType: 1. Set student information

2. Print student information

3. Calculate number of credit hours taken

4. Calculate GPA

5. Calculate billing amount

6. Sort courses according to course number

Page 77: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition
Page 78: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 78

Main Program

1. Declare variables

2. Open input file

3. If input file does not exist, exit program

4. Open output file

5. Get number of students registered and tuition rate

6. Load students’ data

7. Print grade reports

Page 79: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 79

Summary

• 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

Page 80: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 80

Summary

• 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

Page 81: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 81

Summary

• 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 class’s constructor

Page 82: C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

C++ Programming: From Problem Analysis to Program Design, Second Edition 82

Summary

• 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