C Programming: Program Design Including Data Structures, Second Edition - PowerPoint PPT Presentation

1 / 85
About This Presentation
Title:

C Programming: Program Design Including Data Structures, Second Edition

Description:

C++ Programming: Program Design Including Data Structures, Second Edition Chapter 12: Inheritance and Composition Objectives In this chapter you will: Learn about ... – PowerPoint PPT presentation

Number of Views:158
Avg rating:3.0/5.0
Slides: 86
Provided by: Charl207
Category:

less

Transcript and Presenter's Notes

Title: C Programming: Program Design Including Data Structures, Second Edition


1
C Programming Program Design Including Data
Structures, Second Edition
  • Chapter 12 Inheritance and Composition

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

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

4
Two Programming Paradigms
Structural (Procedural) Object-Oriented
PROGRAM PROGRAM
5
Object-Oriented Programming Language Features
  • 1. Data abstraction
  • 2. Inheritance of properties
  • 3. Dynamic binding of operations to objects

6
OOP Terms C Equivalents
  • Object Class object or class
    instance
  • Instance variable Private data member
  • Method Public member function
  • Message passing Function call ( to a public
    member function )

7
What is an object?
OBJECT
set of methods (public member functions) interna
l state (values of private data members)
Operations Data
8
Inheritance Hierarchy Among Vehicles
Every car is a wheeled vehicle.
9
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

10
Inheritance and Composition
  • The two common ways to relate two classes in a
    meaningful way are
  • Inheritance (is-a relationship)
  • Composition (has-a relationship)

11
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

12
Inheritance (continued)
  • Single inheritance derived class has a single
    base class
  • Multiple inheritance derived class has gt 1 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

13
(No Transcript)
14
Inheritance Facts
  • 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 (e.g. shape) can
    be inherited either
  • as public members or
  • class circle public shape
  • as private members by the derived class
  • class circle private shape // or
    equivalent
  • class circle shape // assume
    private

15
Inheritance (continued)
  • 3. The derived class can include additional data
    and/or function members
  • 4. Derived class can redefine public member
    functions of base class
  • Redefinition applies only to objects of the
    derived class, not to the base class
  • 5. All data/function members of the base class
    are also data/function members of the derived
    class

16
class Time Specification
  • // SPECIFICATION FILE ( time.h )
  • class Time
  • public
  • void Set ( int hours , int minutes ,
    int seconds )
  • void Increment ( )
  • void Write ( ) const
  • Time ( int initHrs, int initMins, int
    initSecs ) // constructor
  • Time ( ) // default
    constructor
  • private
  • int hrs
  • int mins
  • int secs

16
17

Class Interface Diagram
Time class
Set
Private data hrs mins secs
Increment
Write
Time
Time
18
Using Inheritance to Add Features
  • // SPECIFICATION FILE ( exttime.h)
  • include time.h
  • enum ZoneType EST, CST, MST, PST, EDT, CDT,
    MDT, PDT
  • class ExtTime public Time
    // Time is the base class
  • public
  • void Set ( int hours, int minutes,
    int seconds ,

  • ZoneType timeZone )
  • void Write ( ) const
  • ExtTime ( int initHrs , int initMins ,
    int initSecs ,
  • ZoneType initZone ) //
    constructor
  • ExtTime ( )
    // default constructor
  • private
  • ZoneType zone // added data member

18
19
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

20

Class Interface Diagram
ExtTime class
Set
Set
Private data hrs mins secs
Increment
Increment
Write
Write
Time
ExtTime
Time
ExtTime
Private data zone
21
Client Code Using ExtTime
  • include exttime.h
  • .
  • .
  • .
  • 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

21
22
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
  • at run time, the base class constructor is
    implicitly called first, before the body of the
    derived classs constructor executes

23
Implementation of ExtTime Class Constructor
with parameters
  • ExtTime ExtTime ( / in / int
    initHrs,
  • / in / int
    initMins,
  • / in / int
    initSecs,
  • / in /
    ZoneType initZone )
  • Time (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

23
// if the base class constructor requires
parameters, they must be passed by the derived
classs constructor
24
Implementation of ExtTimeSet function
  • void ExtTime Set ( / in / int
    hours,
  • / in / int
    minutes,
  • / in / int
    seconds,
  • / in /
    ZoneType time Zone )
  • // 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
  • Time Set (hours, minutes,
    seconds)
  • zone timeZone

24
25
Implementation of ExtTimeWrite Function
  • void ExtTime Write ( ) const
  • // 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
  • Time Write ( )
  • cout ltlt ltlt zoneString zone

25
26
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

27
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

28
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
  • ExtTime ExtTime (int initHrs, int initMins,
  • int initSecs, ZoneType initZone )
  • Time (initHrs, initMins,
    initSecs)

29
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 Xs constructor is executed

30
  • class rectangleType // rectangleType.h
  • public
  • void setDimension(double l, double w)
  • //Function to set the length and width of
    the rectangle.
  • //Postcondition length l width w
  • double getLength() const
  • //Function to return the length of the
    rectangle.
  • //Postcondition The value of length is
    returned.
  • double getWidth() const
  • //Function to return the width of the
    rectangle.
  • //Postcondition The value of width is
    returned.
  • double area() const
  • //Function to return the area of the
    rectangle.
  • //Postcondition The area of the rectangle
    is
  • // calculated and returned.

private double length double width
31
  • include ltiostreamgt // rectangleType.cpp
  • include "rectangleType.h"
  • using namespace std
  • void rectangleTypesetDimension(double l, double
    w)
  • if (l gt 0)
  • length l
  • else
  • length 0
  • if (w gt 0)
  • width w
  • else
  • width 0
  • double rectangleTypegetLength() const

double rectangleTypeperimeter() const
return 2 (length width) void
rectangleTypeprint() const cout ltlt
"Length " ltlt length ltlt " Width "
ltlt width rectangleTyperectangleType(double
l, double w) setDimension(l,
w) rectangleTyperectangleType() //default
constructor length 0 width
0
32
  • class boxType public rectangleType // boxType.h
  • public
  • void setDimension(double l, double w, double
    h)
  • //Function to set the length, width, and
    height
  • //of the box.
  • //Postcondition length l width w
    height h
  • double getHeight() const
  • //Function to return the height of the box.
  • //Postcondition The value of height is
    returned.
  • double area() const
  • //Function to return the surface area of
    the box.
  • //Postcondition The surface area of the
    box is
  • // calculated and returned.
  • double volume() const
  • //Function to return the volume of the box.

33
  • include ltiostreamgt // boxType.cpp
  • include "rectangleType.h"
  • include "boxType.h"
  • using namespace std
  • void boxTypesetDimension(double l, double w,
    double h)
  • rectangleTypesetDimension(l, w)
  • if(h gt 0)
  • height h
  • else
  • height 0
  • double boxTypegetHeight() const
  • return height

double boxTypevolume() const return
rectangleTypearea() height void
boxTypeprint() const rectangleTypeprint
() cout ltlt " Height " ltlt
height boxTypeboxType() //default
constructor height 0.0 boxTypeboxTy
pe(double l, double w, double h)
rectangleType(l, w) // constructor initializer
if(h gt 0) height h else
height 0
34
  • include "rectangleType.h"
  • include "boxType.h"
  • using namespace std
  • int main()
  • rectangleType myRectangle1
    //Line 1
  • rectangleType myRectangle2(8, 6)
    //Line 2
  • boxType myBox1
    //Line 3
  • boxType myBox2(10, 7, 3)
    //Line 4
  • cout ltlt fixed ltlt showpoint ltlt setprecision(2)
    //Line 5
  • cout ltlt "Line 6 myRectangle1 "
    //Line 6
  • myRectangle1.print()
    //Line 7
  • cout ltlt endl
    //Line 8
  • cout ltlt "Line 9 Area of myRectangle1 "

cout ltlt "Line 19 myBox2 "
//Line 19 myBox2.print()
//Line 20 cout ltlt endl
//Line 21
cout ltlt "Line 22 Surface Area of myBox2 "
ltlt myBox2.area() ltlt endl
//Line 22 cout ltlt "Line 23 Volume of myBox2
" ltlt myBox2.volume() ltlt endl
//Line 23 return 0
//line 24
35
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 refers to the base classes
  • include "rectangleType.h"
  • The definitions of the member functions can be
    placed in a separate file
  • "boxType.h
  • Use the preprocessor command (include) to
    include a header file in a program
  • The preprocessor processes the program before it
    is compiled

36
Multiple Inclusions
  • To avoid multiple inclusion of a file in a
    program p.637
  • 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

37
Multiple Inclusions
  • Use certain preprocessor commands in the header
    file (file guard)
  • 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
  • Example Header file test.h
  • ifndef H_test
  • define H_test
  • const int One 1
  • const int Two 2
  • endif

38
  • 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

39
C Stream Classes (continued)
  • istream and ostream provide operations for data
    transfer between memory and devices
  • istream defines the extraction operator (gtgt) and
    functions such as cin, get and ignore
  • ostream defines the insertion operator (ltlt),
    which is used by cout

40
C Stream Classes (continued)
  • ifstream is derived from istream for file input
  • Objects of type ifstream are for file input
  • ofstream is derived from ostream for file output
  • Objects of type ofstream are for file output
  • Header file fstream contains the definitions of
    ifstream and ofstream

41
Protected Members of a Class
  • Private members of a class cannot be directly
    accessed outside the class
  • to give derived class access to a private member
    of a base class
  • 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

42
Public Inheritance
  • class B memberAccessSpecifier A
  • If the memberAccessSpecifier is public, class B
    public A 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 (and friend functions) of B
  • Private members of A are hidden in B and can be
    accessed by member functions (and friend
    functions) of B through public or protected
    members of A

43
Protected Inheritance
  • If the memberAccessSpecifier is protected,
  • class B protected A then
  • Public members of A are protected members of B
    and can be accessed by the member functions (and
    friend functions) of B
  • Protected members of A are protected members of B
    and can be accessed by the member functions (and
    friend functions) of B
  • Private members of A are hidden in B and can be
    accessed by member functions (and friend
    functions) of B through public or protected
    members of A

44
Private Inheritance
  • If the memberAccessSpecifier is private, class B
    private A then
  • Public members of A are private members of B and
    can be accessed by the member functions (and
    friend functions) of B
  • Protected members of A are private members of B
    and can be accessed by the member functions (and
    friend functions) of B
  • Private members of A are hidden in B and can be
    accessed by member functions (and friend
    functions) of B through public or protected
    members of A

45
Inheritance as public, protected, or private
  • Public members of a base class can be inherited
    either as public, protected or private
  • Protected members of a base class can be
    inherited either as protected or private
  • Private members of a base class can be inherited
    either as private

46
Composition
  • In composition, gt member(s) of a class
    are/include objects of another class type
  • Composition is a has-a relation
  • Arguments to the constructor of a member-object
    are specified in the heading part of the
    definition of the constructor

47
Composition (continued)
  • 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
  • Before the enclosing class objects are constructed

48
A TimeCard object has a Time object
  • include time.h
  • class TimeCard
  • public
  • void Punch ( / in / int hours,
  • / in / int
    minutes,
  • / in /
    int seconds )
  • void Print ( ) const
  • TimeCard ( / in / long idNum,
  • / in / int initHrs,
  • / in / int initMins,
  • / in / int
    initSecs )
  • TimeCard ( )
  • private
  • long id
  • Time timeStamp // member(s) of a
    class include
  • //
    objects of another class type

49

TimeCard Class
TimeCard has a Time object
Private data id timeStamp
Print . . .
Private data hrs mins secs
Set
Increment
Write . . .
TimeCard
TimeCard
50
Implementation of TimeCard Class Constructor
  • TimeCard TimeCard ( / in / long 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

50
51
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

52
Two Programming Paradigms
Structural (Procedural) Object-Oriented
PROGRAM PROGRAM
53
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
  • Structured programming
  • Function is a fundamental entity
  • Debug functions
  • Program is a collection of interacting functions
  • Programmer is action-oriented

54
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

55
OOD and OOP (continued)
  • Templates provide parametric polymorphism
  • C provides virtual functions as a means to
    implement polymorphism in an inheritance
    hierarchy
  • Objects are created when class variables are
    declared
  • Objects interact via function calls

56
OOD and OOP (continued)
  • Every object has an internal state and external
    state
  • Private members form the internal state
  • Public members form the external state
  • Only the object can manipulate its internal state

57
Classes, Objects, Operations
  • The hardest part in OOD is
  • 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
  • Suppose we want to Write a program to input the
    dimensions of a cylinder and calculate and print
    the surface area and volume

58
Classes, 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 nouns we visualize a cylinder as
    a class (cylinderType) from which we can create
    many cylinder objects of various dimensions

59
Classes, Objects, Operations
  • The nouns dimensions, surface area, and volume
  • are characteristics of a cylinder
  • Dimensions represent the data
  • After identifying a class, determine
  • Operations that an object can perform
  • Operations that can be performed on an object
  • Information that an object must maintain

60
Operations
  • 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

61
Operations
  • Dimensions of a cylinder represent the data
  • The center of the base, radius of the base, and
    height of the cylinder are the characteristics of
    the dimensions
  • Input data to the object either by a constructor
    or by a mutator function.
  • 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

62
Classes, 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 the
    literature

63
Programming 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

64
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

65
The Input 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
  • .

66
The Input File (continued)
  • A sample-input file is
  • 3 345 // number of students enrolled and
    tuition rate per credit hour
  • Lisa Miller 890238 Y 4 // studentName
    studentID isTuitionPaid numberOfCourses
  • Mathematics MTH345 4 A // courseName
    courseNumber creditHours grade
  • Physics PHY357 3 B
  • ComputerSci CSC478 3 B
  • History HIS356 3 A
  • .

67
Output
  • 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

68
Input and Output
  • Input file containing data in the form given
    above
  • Assume that the name of the input file is
    "astData.txt"
  • Output a file containing output of the form
    given above

69
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

70
Problem 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

71
(No Transcript)
72
Algorithm 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

73
(No Transcript)
74
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

75
  • //personType.h
  • ifndef H_personType
  • define H_personType
  • include ltstringgt
  • using namespace std
  • class personType
  • public
  • void print() const
  • //Function to output the first name and
    last name
  • //in the form firstName lastName.
  • void setName(string first, string last)
  • //Function to set firstName and lastName
    according
  • //to the parameters.

//personTypeImp.cpp include ltiostreamgt include
ltstringgt include "personType.h" using namespace
std void personTypeprint() const cout ltlt
firstName ltlt " " ltlt lastName void
personTypesetName(string first, string
last) firstName first lastName
last string personTypegetFirstName()
const return firstName string
personTypegetLastName() const return
lastName //constructor personTypepersonTyp
e(string first, string last) firstName
first lastName last
76
  • ifndef H_courseType // courseType.h
  • define H_courseType
  • include ltfstreamgt
  • include ltstringgt
  • using namespace std
  • class courseType
  • public
  • void setCourseInfo(string cName, string cNo,
    int credits)
  • //Function to set the course information.
  • //The course information is set according
    to the
  • //incoming parameters.
  • //Postcondition courseName cName
    courseNo cNo
  • // courseCredits credits
  • void print(ostream outF)
  • //Function to print the course information.
  • //This function sends the course
    information to the

include ltiostreamgt // courseType.cpp include
ltfstreamgt include ltstringgt include
ltiomanipgt include "courseType.h" using namespace
std void courseTypesetCourseInfo(string
cName, string cNo, int
credits) courseName cName courseNo
cNo courseCredits credits void
courseTypeprint(ostream outF) outF ltlt
left //Step 1 outF ltlt setw(8) ltlt courseNo ltlt
" " //Step 2 outF ltlt setw(15) ltlt
courseName //Step 3 outF ltlt right
//Step 4 outF ltlt setw(3) ltlt
courseCredits ltlt " " //Step 5 int
courseTypegetCredits() return
courseCredits string courseTypegetCourseNumbe
r() return courseNo string
courseTypegetCourseName() return
courseName courseTypecourseType(string
cName, string cNo, int credits) courseName
cName courseNo cNo courseCredits
credits
77
  • ifndef H_studentType // studentType.h
  • define H_studentType
  • include ltfstreamgt
  • include ltstringgt
  • include "personType.h"
  • include "courseType.h"
  • using namespace std
  • class studentType public personType
  • public
  • void setInfo(string fname, string lName, int
    ID,
  • int nOfCourses, bool isTPaid,
  • courseType courses, char
    courseGrades)
  • //Function to set the student's
    information.
  • //Postcondition The private data members
    are set
  • // according to the
    parameters.

int getHoursEnrolled() //Function to
return the credit hours a student //is
enrolled in. //Postcondition The number of
credit hours are // and
returned. double getGpa() //Function
to return the grade point average.
//Postcondition The gpa is calculated and
returned. double billingAmount(double
tuitionRate) //Function to return the
tuition fees. //Postcondition The billing
amount is calculated //and
returned. private void sortCourses()
//Function to sort the courses.
//Postcondition The array coursesEnrolled is
sorted. // For each course,
its grade is stored in // the
array coursesGrade. Therefore, when //
the array coursesEnrolled is sorted,
the // corresponding entries
in the array // coursesGrade
are adjusted. int sId
//variable to store the student ID int
numberOfCourses //variable to store the number
//of
courses bool isTuitionPaid //variable to
indicate whether the
//tuition is paid courseType
coursesEnrolled6 //array to store the courses
char coursesGrade6 //array to store
the course grades
// Assume max 6 courses endif
78

void studentTypeprint( ostream outF, double
tuitionRate) int i outF ltlt "Student Name "
ltlt getFirstName() ltlt " " ltlt getLastName() ltlt
endl //Step 1 outF ltlt "Student ID
" ltlt sId ltlt endl
//Step 2 outF ltlt "Number of courses enrolled
" ltlt numberOfCourses ltlt endl
//Step 3 outF ltlt endl outF ltlt left outF ltlt
"Course No" ltlt setw(15) ltlt " Course Name" ltlt
setw(8) ltlt "Credits" ltlt setw(6) ltlt "Grade" ltlt
endl //Step 4 outF ltlt
right for (i 0 i lt numberOfCourses i)
//Step
5 coursesEnrolledi.print(outF)
//Step 5a if (isTuitionPaid)
//Step 5b outF ltltsetw(4) ltlt
coursesGradei ltlt endl else outF ltlt
setw(4) ltlt "" ltlt endl outF ltlt endl outF
ltlt "Total number of credit hours " ltlt
getHoursEnrolled() ltlt endl //Step
6 outF ltlt fixed ltlt showpoint ltlt setprecision(2)
//Step 7 if (isTuitionPaid)

//Step 8 outF ltlt "Mid-Semester GPA "
ltlt getGpa() ltlt endl else outF ltlt
" Grades are being held for not paying "
ltlt "the tuition. " ltlt endl outF ltlt
"Amount Due " ltlt billingAmount(tuitionRate)
ltlt endl outF ltlt "------------
--------" ltlt
"-----" ltlt endl ltlt endl
  • include ltiostreamgt // studentType.cpp
  • include ltiomanipgt
  • include ltfstreamgt
  • include ltstringgt
  • include "personType.h"
  • include "courseType.h"
  • include "studentType.h"
  • using namespace std
  • void studentTypesetInfo(string fName, string
    lName,
  • int ID, int nOfCourses, bool isTPaid,
  • courseType courses, char cGrades)
  • int i
  • setName(fName, lName) //set the name
  • sId ID //set the student ID
  • isTuitionPaid isTPaid //set isTuitionPaid

79
  • int studentTypegetHoursEnrolled()
  • int totalCredits 0
  • int i
  • for (i 0 i lt numberOfCourses i)
  • totalCredits coursesEnrolledi.getCredit
    s()
  • return totalCredits
  • double studentTypebillingAmount(double
    tuitionRate)
  • return tuitionRate getHoursEnrolled()
  • double studentTypegetGpa()

void studentTypesortCourses() int i, j int
minIndex courseType temp //variable to swap
the data char tempGrade //variable to swap
the grades string course1 string
course2 for (i 0 i lt numberOfCourses - 1
i) minIndex i for (j i 1 j
lt numberOfCourses j)
//get the course numbers
course1 coursesEnrolled
minIndex.getCourseNumber() course2
coursesEnrolled j.getCourseNumber()
if (course1 gt course2) minIndex
j //end for
// swap temp
coursesEnrolledminIndex
coursesEnrolledminIndex coursesEnrolledi
coursesEnrolledi temp tempGrade
coursesGrademinIndex
coursesGrademinIndex
coursesGradei coursesGradei
tempGrade //end for //end sortCourses
80
  • //Main Program
  • include ltiostreamgt
  • include ltfstreamgt
  • include ltstringgt
  • include "studentType.h"
  • using namespace std
  • const int maxNumberOfStudents 10
  • void getStudentData( ifstream infile,
  • studentType studentList, int
    numberOfStudents)
  • void printGradeReports(ofstream outfile,
    studentType studentList, int numberOfStudents,
    double tuitionRate)
  • int main()
  • studentType studentList maxNumberOfStudents
  • int noOfStudents

void getStudentData(ifstream infile,
studentType
studentList,
int numberOfStudents) //local
variables string fName //variable to
store the first name string lName
//variable to store the last name int ID
//variable to store the student ID
int noOfCourses //variable to store the
number of courses char isPaid
//variable to store Y/N, that is,
//is tuition paid bool
isTuitionPaid //variable to store true/false
string cName //variable to store the course
name string cNo //variable to store
the course number int credits
//variable to store the course credit hours
int count //loop control variable int
i //loop control variable
courseType courses6 //array of objects to
store the
//course information char cGrades6
//array to hold the course grades for
(count 0 count lt numberOfStudents count)
infile gtgt fName gtgt lName gtgt ID gtgt
isPaid //load info Step 1 if (isPaid
'Y') //Step 2
isTuitionPaid true else
isTuitionPaid false infile gtgt
noOfCourses //Step 3 for (i
0 i lt noOfCourses i) // load infoStep 4
infile gtgt cName gtgt cNo gtgt
credits gtgt cGradesi
//Step 4.a
coursesi.setCourseInfo(cName, cNo, credits)
//Step 4.b studentListcount.setInfo(f
Name, lName, ID, noOfCourses,
isTuitionPaid, courses,
cGrades) //load info Step 5 //end for

81
  • // cnt main program
  • void printGradeReports(ofstream outfile,

  • studentType studentList,
  • int
    numberOfStudents,
  • double tuitionRate)
  • int count
  • for (count 0 count lt numberOfStudents
    count)
  • studentList count.print(outfile,
    tuitionRate)

82
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

83
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

84
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 classs
    constructor

85
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
Write a Comment
User Comments (0)
About PowerShow.com