Download presentation
Presentation is loading. Please wait.
1
CHAPTER 14 INHERITANCE AND COMPOSITION
2
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 Explore three types of inheritance: public, protected, and private Learn about composition Become familiar with the three basic principles of object-oriented design
3
Inheritance and Composition
The two common ways to relate two classes in a meaningful way are: 1. Inheritance (“is-a” relationship), and 2. Composition (“has-a” relationship).
4
INHERITANCE 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). We do not want to make the necessary changes directly to the class personType—that 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.
5
The new class that we create from existing classes is called the derived class and the existing classes are called the base classes. 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.
6
Inheritance can be viewed as a tree-like, or hierarchical, structure wherein a base class is shown with its derived classes.
7
class circle: public shape
{ . }; The word public in the heading, called the member access specifier, specifies that all public members of the class shape are inherited as public members by the class circle.
8
The previous definition of circle is equivalent to
class circle: private shape { . }; In this definition, the public members of shape become private members of the class circle. The previous definition of circle is equivalent to class circle: shape
9
The general syntax of a derived class is
class className: memberAccessSpecifier baseClassName { member list }; where memberAccessSpecifier is public, protected, or private. When no memberAccessSpecifier is specified, it is assumed to be a private inheritance.
10
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. 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.
11
Redefining Member Functions of the Base Class
class baseClass { public: void print() const; private: int u; int v; char ch; }; void baseClass::print() const cout<<"Base Class: u = "<<u<<", v = "<<v <<", ch = "<<ch<<endl; }
13
The class derivedClass also overwrites the print function.
class derivedClass: public baseClass { public: void print() const; private: int first; double second; }; The class derivedClass is derived from the class baseClass and it is a public inheritance. All public members of baseClass are inherited as public members of derivedClass. The class derivedClass also overwrites the print function.
15
The class derivedClass has five data members: u, v, ch, first, and second.
To write the definition of the member function print of derivedClass, keep the following in mind: The data members u, v, and ch are private members of the class baseClass. When writing the definition of the function print of derivedClass, we cannot reference u, v, and ch directly. The data members u, v, and ch of the class baseClass are accessible in derivedClass through the public members of baseClass.
16
void derivedClass::print() const
{ baseClass::print(); cout<<"Derived Class: first = "<<first <<", second = "<<second<<endl; cout<<"___________________________________" <<"________"<<endl; } baseClass baseObject; derivedClass derivedObject;
17
baseClass baseObject;
derivedClass derivedObject;
18
Suppose
19
baseObject.print(); derivedObject.print(); In the first statement, the function print of the baseClass is executed In the second statement, the function print associated with the class derivedClass is executed. The output of the first statement is Base Class: u = 5, v = 6, ch = * The output of the second statement is Base Class: u = 12, v = 76, ch = & Derived Class: first = 32, second = 16.38
20
Constructors of Derived and Base Classes
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. The execution of a derived class’s constructor must trigger the execution of one of the base class’s constructors. A call to the base class’s constructor is specified in the heading part of the derived class constructor’s definition.
21
class baseClass { public: void print(); //baseClass Line 1 baseClass(); //baseClass Line 2 baseClass(int x, int y); //baseClass Line 3 baseClass(int x, int y, char w); //baseClass Line 4 private: int u; int v; char ch; };
22
void baseClass::print()
{ cout<<"Base Class: u = "<<u<<", v = "<<v <<", ch = "<<ch<<endl; } //default constructor; baseClass Line 2 baseClass::baseClass() u = 0; v = 0; ch = '*'; //constructor; baseClass Line 3 baseClass::baseClass(int x, int y) u = x; v = y;
23
//constructor; baseClass Line 4
baseClass::baseClass(int x, int y, char w) { u = x; v = y; ch = w; } class derivedClass: public baseClass public: void print(); //derivedClass Line 1 derivedClass(); //derivedClass Line 2 derivedClass(int x, int y, int one, double two); //derivedClass Line 3 derivedClass(int x, int y, char w, int one, double two); //derivedClass Line 4 private: int first; double second; };
25
void derivedClass::print() { baseClass::print();
cout<<"Derived Class: first = "<<first <<", second = "<<second<<endl; cout<<"__________________________________" <<"_________"<<endl; } derivedClass::derivedClass() //default constructor first = 0; second = 0; derivedClass::derivedClass(int x, int y, int one, double two) : baseClass(x,y) //derivedClass constructor Line 3 first = one; second = two;
26
//derivedClass; constructor Line 4
derivedClass::derivedClass(int x, int y, char w, int one, double two) :baseClass(x,y,w) { first = one; second = two; } #include <iostream> #include "baseClass.h" #include "derivedClass.h" using namespace std; int main() baseClass baseObject1; baseClass baseObject2(5,6); baseClass baseObject3(4,8,'K'); derivedClass derivedObject1; derivedClass derivedObject2(12,13,45,8.5); derivedClass derivedObject3(21,23,'Y',76,64.58);
27
cout<<"Line 1: baseObject1: ";
baseObject1.print(); //main Line 1 cout<<"Line 2: baseObject2: "; baseObject2.print(); //main Line 2 cout<<"Line 3: baseObject3: "; baseObject3.print(); //main Line 3 cout<<"Line 4: -*-*-*-*-*-*-*-*-*-*" <<"-*-*-*-*-*-*-*-*-*-*-*-"<<endl; //main Line 4 cout<<"Line 5: Derived Class Objects." <<endl; //main Line 5 cout<<endl; cout<<"Line 6: derivedObject1: "<<endl; derivedObject1.print(); //main Line 6 cout<<"Line 7: derivedObject2: "<<endl; derivedObject2.print(); //main Line 7 cout<<"Line 8: derivedObject3: "<<endl; derivedObject3.print(); //main Line 8 return 0; }
28
OUTPUT: Line 1: baseObject1: Base Class: u = 0, v = 0, ch = * Line 2: baseObject2: Base Class: u = 5, v = 6, ch = * Line 3: baseObject3: Base Class: u = 4, v = 8, ch = K Line 4: -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- Line 5: Derived Class Objects. Line 6: derivedObject1: Base Class: u = 0, v = 0, ch = * Derived Class: first = 0, second = 0 ___________________________________________ Line 7: derivedObject2: Base Class: u = 12, v = 13, ch = * Derived Class: first = 45, second = 8.5 Line 8: derivedObject3: Base Class: u = 21, v = 23, ch = Y Derived Class: first = 76, second = 64.58
29
Example 14-1 class partTimeEmployee: public personType { public:
void print(); //Function to output the first name, last name, //and the wages in the form: //firstName lastName wages are $$$$.$$ double calculatePay(); void setNameRateHours(string first, string last, double rate, double hours); partTimeEmployee(string first, string last, double rate, double hours); partTimeEmployee(); private: double payRate; //store the pay rate double hoursWorked; //store the hours worked };
31
void partTimeEmployee::print()
{ personType::print(); //print the name of the employee cout<<" wages are : "<<calculatePay()<<endl; } double partTimeEmployee::calculatePay() return (payRate * hoursWorked); void partTimeEmployee::setNameRateHours (string first, string last, double rate, double hours) personType::setName(first,last); payRate = rate; hoursWorked = hours;
32
partTimeEmployee::partTimeEmployee(string first,
string last, double rate, double hours) : personType(first, last) { payRate = rate; hoursWorked = hours; } //default constructor partTimeEmployee:: partTimeEmployee() payRate = 0; hoursWorked = 0;
33
Header File of a Derived Class
//Header file ptEmployee.h #include "person.h" class partTimeEmployee: public personType { public: void print() const; double calculatePay(); void setNameRateHours(string, string, double, double); partTimeEmployee(string, string, partTimeEmployee(); //default constructor private: double payRate; double hoursWorked; };
34
Multiple Inclusions of a Header File
//Header file test.h const int one = 1; const int two = 2; Suppose that the header file testA.h includes the file test.h to make use of the identifiers one and two. //Header file testA.h #include "test.h" .
35
// Program headerTest.cpp #include "test.h" #include "testA.h"
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 declared. To avoid multiple inclusion of a file in a program we use certain preprocessor commands in the header file.
36
//Header file test.h #ifndef H_test #define H_test const int one = 1; const int two = 2; #endif a. #ifndef H_test means “if not defined H_test” b. #define H_test means “define H_test” c. #endif means “end if” H_test is a preprocessor identifier. All header files are written using similar preprocessor commands.
37
C++ Stream Classes
38
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. 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.
39
The class istream defines the extraction operator, >>, and functions such as get and ignore.
The class ostream defines the insertion operator, <<, 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. Objects of the type ifstream are used for file output; objects of the type ofstream are used for file output. The header file fstream contains the definition of the classes ifstream and ofstream.
40
Protected 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. 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.
41
Inheritance as public, protected, or private
class B: memberAccessSpecifier A { . }; memberAccessSpecifier is either public, protected, or private.
42
1. If memberAccessSpecifier is public, then
a. The public members of A are public members of B. They can be directly accessed in class B. b. The protected members of A are protected members of B. They can be directly accessed by the member functions (and friend functions) of B. c. The private members of A are hidden in B. They can be accessed by the member functions (and friend functions) of B through the public or protected members of A. 2. If memberAccessSpecifier is protected, then a. The public members of A are protected members of B. They can be accessed by the member functions (and friend functions) of B. b. The protected members of A are protected members of B. They can be accessed by the member functions (and friend functions) of B.
43
3. If memberAccessSpecifier is private, then
a. The public members of A are private members of B. They can be accessed by the member functions (and friend functions) of B. b. The protected members of A are private members of B. They can be accessed by the member functions (and friend functions) of B. c. The private members of A are hidden in B. They can be accessed by the member functions and (and friend functions) of B through the public or protected members of A.
44
Example 14-2: (Accessing protected members in the derived class.)
class bClass { public: void setData(double); void setData(char, double); void print() const; bClass(char = '*', double = 0.0); protected: char bCh; private: double bX; };
45
void bClass::setData(double u)
{ bX = u; } void bClass::setData(char ch, double u) bCh = ch; void bClass::print() const cout<<"Base class: bCh = "<<bCh<<", bX = "<<bX<<endl; bClass::bClass(char ch, double u)
46
class dClass: public bClass { public: void setData(char, double, int);
void print() const; private: int dA; }; void dClass::setData(char ch, double v, int a) bClass::setData(v); bCh = ch; //initialize bCh using the assignment //statement dA = a; }
47
void dClass::print() const
{ bClass::print(); cout<<"Derived class dA = "<<dA<<endl; } //Accessing protected members of a base class //in the derived class #include <iostream> #include "protectMembClass.h" #include "protectMembInDerivedCl.h" using namespace std; int main() bClass bObject; //Line 1 dClass dObject; //Line 2
48
bObject.print(); //Line 3
cout<<endl; //Line 4 cout<<"*** Derived class object ***"<<endl; //Line 5 dObject.setData('&', 2.5, 7); //Line 6 dObject.print(); //Line 7 return 0; } Output Base class: bCh = *, bX = 0 *** Derived class object *** Base class: bCh = &, bX = 2.5 Derived class dA = 7
49
COMPOSITION In composition one (or more) member(s) of a class is an object of another class type. Composition is a “has-a” relation.
50
class dateType { public: void setDate(int month, int day, int year); void getDate(int& month, int& day, int& year); void printDate() const; dateType(int month, int day, int year); dateType(); private: int dMonth; //variable to store the month int dDay; //variable to store the day int dYear; //variable to store the year };
52
void dateType::setDate(int month, int day, int year)
{ dMonth = month; dDay = day; dYear = year; } void dateType::getDate(int& month, int& day, int& year) month = dMonth; day = dDay; year = dYear; void dateType::printDate() const cout<<dMonth<<"-"<<dDay<<"-"<<dYear;
53
//constructor with parameter
dateType:: dateType(int month, int day, int year) { dMonth = month; dDay = day; dYear = year; } dateType:: dateType() //default parameter dMonth = 1; dDay = 1; dYear = 1900;
54
class personalInfo { public: void setpersonalInfo(string first, string last, int month, int day, int year, int ID); void printpersonalInfo () const; personalInfo(string first, string last, personalInfo(); private: personType name; dateType bDay; int personID; };
56
personalInfo student;
When the object student enters its scope, the objects bDay and name, which are members of student, also enter their scopes; as a result, one of their constructors is executed. The arguments to the constructor of a member-object (such as bDay) 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 constructor’s member initialization list), and before the enclosing class objects are constructed. The object name is initialized first, then bDay, and finally student.
57
void personalInfo::setpersonalInfo(string first,
string last, int month, int day, int year, int ID) { name.setName(first,last); bDay.setDate(month,day,year); personID = ID; } void personalInfo::printpersonalInfo () const name.print(); cout<<"’s date of birth is "; bDay.printDate(); cout<<endl; cout<<"and personal ID is "<<personID;
58
personalInfo::personalInfo(string first, string last,
int month, int day, int year, int ID) : name(first,last), bDay(month,day,year) { personID = ID; } personalInfo::personalInfo() //default constructor personID = 0;
59
In the case of inheritance we use the class name to invoke the base class’s constructor while in the case of composition we use the member object name to invoke the constructor of the member object.
60
Objected Oriented Design (OOD) and Objected Oriented Programming (OOP)
The fundamentals of OOD are: 1. Encapsulation—combine data and operations on data in a single unit. 2. Inheritance—create new objects from existing objects. 3. Polymorphism—the ability to use the same expression to denote different operations.
61
In OOD an object is a fundamental entity, while in structured programming a function is a fundamental entity. 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. The object-oriented programming (OOP) implements OOD. C++ supports OOP through the use of classes. A polymorphic function or operator has many forms. In C++ 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.
62
Objects are created when class variables are declared
Objects are created when class variables are declared. Objects interact with each other via function call. 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.
63
Identifying Classes, Objects, and 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. 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—program, dimensions, cylinder, surface area, and volume—we can easily visualize cylinder to be a class— say, cylinderType—from which we can create many cylinder objects of various dimensions.
64
The nouns—dimensions, surface area, and volume—are 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 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 description—write, input, calculate, and print—the possible operations for a cylinder object are input, calculate, and print. For the cylinderType class, the dimensions represent the data. The center of the base, radius of the base, and height of the cylinder are the characteristics of the dimensions.
65
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. 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.
66
PROGRAMMING EXAMPLE: GRADE REPORT
This programming example further illustrates the concepts of inheritance and composition. 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. 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.
67
The data is stored in a file in the following form:
studentName studentID isTuitionPaid numberOfCourses courseName courseNumber creditHours grade . The first line indicates the number of students enrolled and the tuition rate per credit hour. The students’ data is given thereafter.
68
A sample-input file is:
3 345 Lisa Miller Y 4 Mathematics MTH345 4 A Physics PHY357 3 B ComputerSci CSC478 3 B History HIS356 3 A .
69
The desired output for each student is of the form:
Student Name: Lisa Miller Student ID: Number of courses enrolled: 4 Course No Course Name Credits Grade CSC ComputerSci B HIS History A MTH Mathematics A PHY Physics B Total number of credits: 13 Mid-Semester GPA: 3.54
70
Input: A file containing data in the form given above
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 "a:stData.txt". Output: A file containing output of the form given above.
71
Problem Analysis and Algorithm Design
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 student’s grade. 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.
73
class courseType { public: void setCourseInfo(string cName, string cNo, char grade, int credits); void print(bool isGrade); void print(ofstream& outp, bool isGrade); int getCredits(); void getCourseNumber(string& cNo); char getGrade(); courseType(string cName = "", string cNo = "", char grade = '*', int credits = 0); private: string courseName; //variable to store the course name string courseNo; //variable to store the course number char courseGrade; //variable to store the grade int courseCredits; //variable to store the grade };
74
void courseType::setCourseInfo(string cName,
string cNo, char grade, int credits) { courseName = cName; courseNo = cNo; courseGrade = grade; courseCredits = credits; } void courseType::print(bool isGrade) { cout<<left; //Step 1 cout<<setw(8)<<courseNo<<" "; //Step 2 cout<<setw(15)<<courseName; //Step 3 cout.unsetf(ios::left); //Step 4 cout<<setw(3)<<courseCredits<<" "; //Step 5 if(isGrade) //Step 6 cout<<setw(4)<<courseGrade<<endl; else cout<<setw(4)<<"***"<<endl;
75
outp<<left; //Step 1
void courseType::print(ofstream& outp, bool isGrade) { outp<<left; //Step 1 outp<<setw(8)<<courseNo<<" "; //Step 2 outp<<setw(15)<<courseName; //Step 3 outp.unsetf(ios::left); //Step 4 outp<<setw(3)<<courseCredits<<" "; //Step 5 if(isGrade) //Step 6 outp<<setw(4)<<courseGrade<<endl; else outp<<setw(4)<<"***"<<endl; } courseType::courseType(string cName, string cNo, char grade, int credits) courseName = cName; courseNo = cNo; courseGrade = grade; courseCredits = credits;
76
int courseType::getCredits()
{ return courseCredits; } char courseType::getGrade() return courseGrade; void courseType::getCourseNumber(string& cNo) cNo = courseNo;
77
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. 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 person’s first name and last name. We can derive the class studentType to keep track of a student’s information from the class personType, and one member of this class is of the type courseType.
78
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 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.
79
class studentType: public personType
{ public: void setInfo(string fname, string lName, int ID, int nOfCourses, bool isTPaid, courseType courses[]); void print(double tuitionRate); void print(ofstream& out, double tuitionRate); studentType(); int getHoursEnrolled(); double getGpa(); double billingAmount(double tuitionRate); private: void sortCourses(); int sId; //variable to store the student ID int numberOfCourses; bool isTuitionPaid; courseType coursesEnrolled[6]; };
81
void studentType::setInfo(string fName, string lName,
int ID, int nOfCourses, bool isTPaid, courseType courses[]) { int i; personType::setName(fName,lName); //set the name sId = ID; //set the student ID isTuitionPaid = isTPaid; //set isTuitionPaid numberOfCourses = nOfCourses ; for(i = 0; i < numberOfCourses; i++) //set the array coursesEnrolled[i] = courses[i]; //coursesEnrolled sortCourses(); //sort the array coursesEnrolled }
82
studentType::studentType()
{ numberOfCourses = 0; sId = 0; isTuitionPaid = false; } void studentType::print(double tuitionRate) int i; cout<<"Student Name: "; //Step 1 personType::print(); //Step 1 cout<<endl; cout<<"Student ID: "<<sId<<endl; //Step 2 cout<<"Number of courses enrolled: " <<numberOfCourses<<endl; //Step 3 cout<<left; //set output left-justified
83
cout<<"Course No"<<setw(15)<<" Course Name"
<<setw(8)<<"Credits" <<setw(6)<<"Grade"<<endl; //Step 4 cout.unsetf(ios::left); for(i = 0; i < numberOfCourses; i++) //Step 5 coursesEnrolled[i].print(isTuitionPaid); cout<<endl; cout<<"Total number of credit hours: " <<getHoursEnrolled()<<endl; //Step 6 cout<<fixed<<showpoint<<setprecision(2); //Step 7 if(isTuitionPaid) //Step 8 cout<<"Mid-Semester GPA: "<<getGpa()<<endl; else { cout<<"*** Grades are being held for not paying " <<"the tuition. ***"<<endl; cout<<"Amount Due: "<<billingAmount(tuitionRate) <<endl; }
84
cout<<"-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*"
<<"-*-*-*-*-*-*-"<<endl<<endl; } void studentType::print(ofstream& outp, double tuitionRate) { int i; string first; string last; personType::getName(first,last); outp<<"Student Name: "<<first<<" "<<last<<endl; outp<<"Student ID: "<<sId<<endl; outp<<"Number of courses enrolled: " <<numberOfCourses<<endl; outp<<endl; outp<<left; outp<<"Course No"<<setw(15)<<" Course Name" <<setw(8)<<"Credits" <<setw(6)<<"Grade"<<endl; outp.unsetf(ios::left);
85
for(i = 0; i < numberOfCourses; i++)
coursesEnrolled[i].print(outp,isTuitionPaid); outp<<endl; outp<<"Total number of credit hours: " <<getHoursEnrolled()<<endl; outp<<fixed<<showpoint<<setprecision(2); if(isTuitionPaid) outp<<"Mid-Semester GPA: "<<getGpa()<<endl; else { outp<<"*** Grades are being held for not paying " <<"the tuition. ***"<<endl; outp<<"Amount Due: "<<billingAmount(tuitionRate) <<endl; } outp<<"-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*" <<"-*-*-*-*-"<<endl<<endl;
86
int studentType::getHoursEnrolled()
{ int totalCredits = 0; int i; for(i = 0; i < numberOfCourses; i++) totalCredits += coursesEnrolled[i].getCredits(); return totalCredits; } double studentType::billingAmount(double tuitionRate) return tuitionRate * getHoursEnrolled();
87
double studentType::getGpa() { int i; double sum = 0.0;
for(i = 0; i < numberOfCourses; i++) switch(coursesEnrolled[i].getGrade()) case 'A': sum += coursesEnrolled[i].getCredits() * 4; break; case 'B': sum += coursesEnrolled[i].getCredits() * 3; case 'C': sum += coursesEnrolled[i].getCredits() * 2; case 'D': sum += coursesEnrolled[i].getCredits() * 1; case 'F': sum += coursesEnrolled[i].getCredits() * 0; default: cout<<"Invalid Course Grade"<<endl; } return sum / getHoursEnrolled();
88
void studentType::sortCourses() { int i,j; int minIndex;
courseType temp; //variable to swap data string course1; string course2; for(i = 0; i < numberOfCourses - 1; i++) minIndex = i; for(j = i + 1; j < numberOfCourses; j++) //get course numbers coursesEnrolled[minIndex].getCourseNumber(course1); coursesEnrolled[j].getCourseNumber(course2); if(course1 > course2) minIndex = j; }//end for temp = coursesEnrolled[minIndex]; coursesEnrolled[minIndex] = coursesEnrolled[i]; coursesEnrolled[i] = temp; }//end sortCourses
89
Main 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.
90
Variables studentType studentList[maxNumberOfStudents];
//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
91
Function getStudentData void getStudentData(ifstream& infile,
studentType studentList[], int numberOfStudents) { //Local variable 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; char isPaid; bool isTuitionPaid; 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 char grade; //variable to store the course grade int count; //loop control variable int i; //loop control variable
92
courseType courses[6];
for(count = 0; count < numberOfStudents; count++) { infile>>fName>>lName>>ID>>isPaid; //Step 1 if(isPaid == 'Y') //Step 2 isTuitionPaid = true; else isTuitionPaid = false; infile>>noOfCourses; //Step 3 for(i = 0; i < noOfCourses; i++) //Step 4 infile>>cName>>cNo>>credits>>grade; courses[i].setCourseInfo(cName, cNo, credits, grade); } studentList[count].setInfo(fName, lName, ID, noOfCourses, isTuitionPaid, courses); }//end for
93
Function printGradeReports
void printGradeReports(ofstream& outfile, studentType studentList[], int numberOfStudents, double tuitionRate) { int count; for(count = 0; count < numberOfStudents; count++) studentList[count].print(outfile,tuitionRate); }
94
Program Listing //Header file courseType.h #ifndef H_courseType
#define H_courseType #include <fstream> #include <string> using namespace std; //The definition of the class courseType goes here. . #endif
95
//Implementation file courseTypeImp.cpp
#include <iostream> #include <fstream> #include <string> #include <iomanip> #include "courseType.h" using namespace std; //The definitions of the member functions of the class //courseType go here. . //Header file personType.h #ifndef personType_H #define personType_H //The definition of the class personType goes here. #endif
96
//Implementation File personTypeImp.cpp
#include <iostream> #include <string> #include "person.h" using namespace std; //The definitions of the member functions of the class //personType go here. .
97
//Header file studentType.h
#ifndef H_studentType #define H_studentType #include <fstream> #include <string> #include "person.h" #include "courseType.h" using namespace std; //The definition of the class studentType goes here. . #endif
98
//Implementation file studentTypeImp.cpp
#include <iostream> #include <iomanip> #include <fstream> #include <string> #include "person.h" #include "courseType.h" #include "studentType.h" using namespace std; //The definitions of the member functions of the class //studentType go here. .
99
//Main program #include <iostream> #include <fstream> #include <string> #include "studentType.h" using namespace std; const int maxNumberOfStudents = 10; void getStudentData(ifstream& infile, studentType studentList[], int numberOfStudents); void printGradeReports(ofstream& outfile, int numberOfStudents, double tuitionRate); int main() { studentType studentList[maxNumberOfStudents]; int noOfStudents; double tuitionRate; ifstream infile; ofstream outfile;
100
infile.open("a:stData.txt");
if(!infile) { cout<<"Input file does not exist. " <<"Program terminates."<<endl; return 1; } outfile.open("a:sDataOut.txt"); infile>>noOfStudents; //get the number of students infile>>tuitionRate; //get the tuition rate getStudentData(infile, studentList, noOfStudents); printGradeReports(outfile, studentList, noOfStudents, tuitionRate); return 0;
101
//Place the definitions of the functions
//getStudentData and printGradeReports //here
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.