Chapter11 230 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 84

Chapter11:

InheritanceandComposition
Objectives
Inthischapter,youwill:
Learnaboutinheritance
Learnaboutderivedandbaseclasses
Redefinethememberfunctionsofabaseclass
Examinehowtheconstructorsofbaseandderivedclasses
work
Learnhowtoconstructtheheaderfileofaderivedclass

C++ Programming: Program Design Including Data Structures, Sixth Edition 2


Objectives(contd.)
Inthischapter,youwill(contd.):
LearnabouttheC++streamhierarchy
Explorethreetypesofinheritance:public,
protected,andprivate
Learnaboutcomposition(aggregation)
Becomefamiliarwiththethreebasicprinciplesofobject
orienteddesign

C++ Programming: Program Design Including Data Structures, Sixth Edition 3


Introduction
Twocommonwaystorelatetwoclassesina
meaningfulwayare:
Inheritance(isa relationship)
Composition,oraggregation:(hasa relationship)

C++ Programming: Program Design Including Data Structures, Sixth Edition 4


Inheritance
Inheritance:isa relationship
Example:everyemployeeisaperson
Inheritanceallowscreationofnewclassesfrom
existingclasses
Derivedclasses:newclassescreatedfromtheexistingclass
Baseclass:theoriginalclass
Derivedclassinherits thepropertiesofitsbase
classes

C++ Programming: Program Design Including Data Structures, Sixth Edition 5


Inheritance(contd.)
Inheritancehelpsreducesoftwarecomplexity
Singleinheritance:derivedclasshasasinglebase
class
Multipleinheritance:derivedclasshasmorethan
onebaseclass
Publicinheritance:allpublicmembersofbaseclass
areinheritedaspublicmembersbyderivedclass
Mostcommonlyused

C++ Programming: Program Design Including Data Structures, Sixth Edition 6


Inheritance(contd.)
Inheritancecanbeviewedasatreelike,or
hierarchical,structurebetweenthebaseclassandits
derivedclasses

C++ Programming: Program Design Including Data Structures, Sixth Edition 7


Inheritance(contd.)
Syntaxofaderivedclass:

o memberAccessSpecifier ispublic,protected,
orprivate (default)
private membersofabaseclassareprivate to
thebaseclass
o Derivedclasscannotdirectly accessthem

C++ Programming: Program Design Including Data Structures, Sixth Edition 8


Inheritance (continued)
class circle: public shape
{

}

class circle: private shape


{

}

The public members of shape are private to circle.

C++ Programming: Program Design Including Data Structures, Sixth Edition 9


Inheritance(contd.)
public membersofbaseclasscanbeinheritedas
public orprivate members
Derivedclasscanincludeadditionalmembers(data
and/orfunctions)
Derivedclasscanredefinepublic member
functionsofthebaseclass
Appliesonlytotheobjectsofthederived class
Allmembersvariablesofthebaseclassarealso
membervariablesofthederivedclass

C++ Programming: Program Design Including Data Structures, Sixth Edition 10


Redefining(Overriding)Member
FunctionsoftheBaseClass
Toredefine apublic memberfunction:
Correspondingfunctioninderivedclassmusthavesame
name/number/typesofparameters
Ifderivedclassoverrides apublic member
functionofthebaseclass,thentocallthebaseclass
function,specify:
Nameofthebaseclass
Scoperesolutionoperator(::)
Functionnamewithappropriateparameterlist

C++ Programming: Program Design Including Data Structures, Sixth Edition 11


RedefiningMemberFunctionsoftheBase
Class(contd.)

C++ Programming: Program Design Including Data Structures, Sixth Edition 12


RedefiningMemberFunctionsof
theBaseClass(contd.)
boxType isderivedfromrectangleType,andit
isapublic inheritance
Alsooverridesprint andarea

C++ Programming: Program Design Including Data Structures, Sixth Edition 13


class rectangleType
{
public:
void setDimension(double l, double w);
double getLength() const;
double getWidth() const;
double area() const;
double perimeter() const;
void print() const;
rectangleType();
rectangleType(double l, double w);

private:
double length;
double width;
};

C++ Programming: Program Design Including Data Structures, Sixth Edition 14


#include <iostream>
#include "rectangleType.h"
using namespace std;

void rectangleType::setDimension(double l, double w)


{ if (l >= 0)
length = l;
else
length = 0;
if (w >= 0)
width = w;
else
width = 0;
}
double rectangleType::getLength() const
{
return length;
}

double rectangleType::getWidth() const


{
return width;
} Programming: Program Design Including Data Structures, Third Edition
C++ 15
double rectangleType::area() const
{
return length * width;
}

double rectangleType::perimeter() const


{
return 2 * (length + width);
}
void rectangleType::print() const
{
cout << "Length = " << length << "; Width = " << width;
}
rectangleType::rectangleType(double l, double w)
{
setDimension(l, w);
}
rectangleType::rectangleType()
{
length = 0;
width = 0;
}
16
class boxType: public rectangleType // Inheritance
{
public:
void setDimension(double l, double w, double h); // Overloading

double getHeight() const;

double area() const; // Overrides area() of rectangle

double volume() const;

void print() const; // Overrides print() of rectangle

boxType();

boxType(double l, double w, double h);

private:
double height;
};

17
#include <iostream>
#include "rectangleType.h"
#include "boxType.h"

using namespace std;

void boxType::setDimension(double l, double w, double h)


{
rectangleType::setDimension(l, w);

if (h >= 0)
height = h;
else
height = 0;
}

double boxType::getHeight() const


{
return height;
}

18
double boxType::area() const
{ return 2 * (getLength() * getWidth()
+ getLength() * height
+ getWidth() * height); // No need for ::
}
double boxType::volume() const
{
return rectangleType::area() * height;
}
void boxType::print() const
{ rectangleType::print();
cout << "; Height = " << height;
}
boxType::boxType() //default constructor. Automatically calls
{ //default constructor of rectangleType
height = 0.0;
}
boxType::boxType(double l, double w, double h) : rectangleType(l, w)
{ if (h >= 0)
height = h;
else
height = 0;
} Programming: Program Design Including Data Structures, Third Edition
C++ 19
ConstructorsofDerivedandBase
Classes
Derivedclassconstructorcannotdirectlyaccess
private membersofthebaseclass
Itcandirectlyinitializeonlypublic membervariablesof
thebaseclass
Whenaderivedobjectisdeclared,itmustexecute
oneofthebaseclassconstructors
Calltobaseclassconstructorisspecifiedinheading
ofderivedclassconstructordefinition

C++ Programming: Program Design Including Data Structures, Sixth Edition 20


ConstructorsofDerivedandBase
Classes

21
#include <iostream>
#include <iomanip>

#include "rectangleType.h"
#include "boxType.h
using namespace std;

int main()
{
rectangleType myRectangle1, myRectangle2(8, 6);
boxType myBox1, myBox2(10, 7, 3);

cout << fixed << showpoint << setprecision(2);


cout << "myRectangle1: ";
myRectangle1.print(); // myRectangle1: Length = 0.00; Width = 0.00
cout << endl;

cout << "Area of myRectangle1: " << myRectangle1.area() << endl;


// Area of myrectangle1: 0.00
cout << "myRectangle2: ";
myRectangle2.print(); // myRectangle2: Length = 8.00; Width = 6.00
cout << endl;
C++ Programming: Program Design Including Data Structures, Third Edition 22
cout << "Area of myRectangle2: " << myRectangle2.area() << endl;
// Area of myRectangle2: 48.00
cout << "myBox1: ";
myBox1.print(); // myBox1: Length = 0.00; Width = 0.00; Height = 0.00
cout << endl;

cout << "Surface Area of myBox1: " << myBox1.area() << endl;
// Surface Area of myBox1: 0.00
cout << "Volume of myBox1: " << myBox1.volume() << endl;
// Volume of myBox1: 0.00
cout << "myBox2: ";
myBox2.print(); // myBox2: Length = 10.00; Width = 7.00; Height = 3.00
cout << endl;

cout << "Surface Area of myBox2: " << myBox2.area() << endl;
// Surface Area of myBox2: 242.00
cout << "Volume of myBox2: " << myBox2.volume() << endl;
// Volume of myBox2: 210.00
return 0;
}

23
DestructorsinaDerivedClass
Destructors:usedtodeallocatedynamicmemory
allocatedbytheobjectsofaclass
Whenaderivedclassobjectgoesoutofscope
Automaticallyinvokesitsdestructor
Whenthedestructorofthederivedclassexecutes
Automaticallyinvokesthedestructorofthebaseclass

C++ Programming: Program Design Including Data Structures, Sixth Edition 24


HeaderFileofaDerivedClass
Todefinenewclasses,createnewheaderfiles
Tocreatenewderivedclasses,includecommands
thatspecifywherethebaseclassdefinitionscanbe
found
Definitionsofthememberfunctionscanbeplacedin
aseparatefile

C++ Programming: Program Design Including Data Structures, Sixth Edition 25


MultipleInclusionsofaHeader
File
Usethepreprocessorcommand(#include)to
includeaheaderfileinaprogram
Preprocessorprocessestheprogrambeforeitiscompiled
Toavoidmultipleinclusionofafileinaprogram,use
certainpreprocessorcommandsintheheaderfile

C++ Programming: Program Design Including Data Structures, Sixth Edition 26


Multiple Inclusions
For every header file we include the following:
#ifndef H_rectangleType
#define H_rectangleType

// Body of the header file

#endif

27
Multiple Inclusions of a Header
File
Problem: Solution:

28
C++StreamClasses
ios isthebaseclassforallstreamclasses
Containsformattingflagsandmemberfunctionsto
access/modifytheflagsettings

C++ Programming: Program Design Including Data Structures, Sixth Edition 29


C++StreamClasses(contd.)
istream andostream provideoperationsfor
datatransferbetweenmemoryanddevices
istream definestheextractionoperator(>>)and
functionsget andignore
ostream definestheinsertionoperator(<<)whichis
usedbycout
ifstream/ofstream objectsareforfileI/O
Headerfilefstream containsthedefinitionsforthese

C++ Programming: Program Design Including Data Structures, Sixth Edition 30


ProtectedMembersofaClass
Derivedclasscannotdirectlyaccessprivate
membersofitbaseclass
Togiveitdirectaccess,declarethatmemberas
protected

C++ Programming: Program Design Including Data Structures, Sixth Edition 31


Inheritanceaspublic,protected,
orprivate
AssumeclassBisderivedfromclassAwith

IfmemberAccessSpecifier ispublic:
public membersofA arepublic inB,andcanbe
directlyaccessedinclassB
protected membersofA areprotected inB,andcan
bedirectlyaccessedbymemberfunctions(andfriend
functions)ofB
private membersof A arehiddeninB andcanbe
accessedonlythroughpublic orprotected members
ofA

C++ Programming: Program Design Including Data Structures, Sixth Edition 32


Inheritanceaspublic,protected,or
private (contd.)
IfmemberAccessSpecifier isprotected:
public membersofA areprotected membersofB
andcanbeaccessedbythememberfunctions(andfriend
functions)ofB
protected membersofA areprotected membersof
B andcanbeaccessedbythememberfunctions(and
friendfunctions)ofB
private membersofA arehiddeninB andcanbe
accessedonlythroughpublic orprotected members
ofA

C++ Programming: Program Design Including Data Structures, Sixth Edition 33


Inheritanceaspublic,protected,or
private (contd.)
IfmemberAccessSpecifier isprivate:
public membersofA areprivate membersofB and
canbeaccessedbymemberfunctionsofB
protected membersofA areprivate membersofB
andcanbeaccessedbymemberfunctions(andfriend
functions)ofB
private membersofA arehiddeninB andcanbe
accessedonlythroughpublic/protected membersof
A

C++ Programming: Program Design Including Data Structures, Sixth Edition 34


#ifndef H_protectMembClass
#define H_protectMembClass

class bClass
{
public:
void setData(double);
void setData(char, double);
void print() const;

bClass(char = '*', double = 0.0);

protected:
char bCh;

private:
double bX;
};

#endif

35
#include <iostream>
#include "protectMembClass.h"
using namespace std;

void bClass::setData(double u)
{
bX = u;
}
void bClass::setData(char ch, double u)
{
bCh = ch;
bX = u;
}
void bClass::print() const
{
cout << "Base class: bCh = " << bCh << ", bX = " << bX << endl;
}

bClass::bClass(char ch, double u)


{
bCh = ch;
bX = u;
}
#ifndef H_protectMembInDerivedCl
#define H_protectMembInDerivedCl

#include "protectMembClass.h"

class dClass: public bClass


{
public:
void setData(char, double, int);
void print() const;

private:
int dA;
};

#endif

37
#include <iostream>
#include "protectMembClass.h"
#include "protectMembInDerivedCl.h"

using namespace std;

void dClass::setData(char ch, double v, int a)


{
bClass::setData(v); // indirect access of private member

bCh = ch; // direct access of protected member

dA = a;
}

void dClass::print() const


{
bClass::print();

cout << "Derived class dA = " << dA << endl;


}

38
#include <iostream>
#include "protectMembClass.h"
#include "protectMembInDerivedCl.h"

using namespace std;

int main()
{
bClass bObject;
dClass dObject;

bObject.print();
cout << endl; // Base class: bCh = *, bX = 0

cout << "*** Derived class object ***" << endl;

dObject.setData('&', 2.5, 7);

dObject.print(); // Base class: bCh = &, bX = 2.5


// Derived class dA = 7
return 0;
}
Composition(Aggregation)
Incomposition,oneormoremember(s)ofaclass
areobjectsofanotherclasstype
Composition(aggregation):hasa relation
Argumentstotheconstructorofamemberobject
arespecifiedintheheadingpartofthedefinitionof
theconstructor

C++ Programming: Program Design Including Data Structures, Sixth Edition 40


Composition(Aggregation)(contd.)
Memberobjectsofaclassareconstructedinthe
ordertheyaredeclared
Notintheorderlistedintheconstructorsmember
initializationlist
Theyareconstructedbeforethecontainingclass
objectsareconstructed

C++ Programming: Program Design Including Data Structures, Sixth Edition 41


#ifndef dateType_H
#define dateType_H

class dateType
{
public:
void setDate(int month, int day, int year);
int getDay() const;
int getMonth() const;
int getYear() const;
void printDate() const;
dateType(int month = 1, int day = 1, int year = 1900);

private:
int dMonth;
int dDay;
int dYear;
};

#endif

42
#include <iostream>
#include "dateType.h"
using namespace std;
void dateType::setDate(int month, int day, int year)
{ dMonth = month;
dDay = day;
dYear = year;
}
int dateType::getDay() const
{ return dDay;
}
int dateType::getMonth() const
{ return dMonth;
}
int dateType::getYear() const
{ return dYear;
}
void dateType::printDate() const
{ cout<<dMonth<<"-"<<dDay<<"-"<<dYear;
}
dateType::dateType(int month, int day, int year)
{
dMonth = month; dDay = day; dYear = year;
} Programming: Program Design Including Data Structures, Third Edition
C++ 43
#include <string>
using namespace std;

class personType
{
public:
void print() const;

void setName(string first, string last);

string getFirstName() const;

string getLastName() const;

personType(string first = "", string last = "");

private:
string firstName;
string lastName;
};

44
#include <iostream>
#include <string>
#include "personType.h"
using namespace std;
void personType::print() const
{
cout << firstName << " " << lastName;
}
void personType::setName(string first, string last)
{ firstName = first;
lastName = last;
}
string personType::getFirstName() const
{ return firstName;
}
string personType::getLastName() const
{ return lastName;
}
personType::personType(string first, string last)

{ firstName = first;
lastName = last;
} 45
#ifndef personalInfo_H
#define personalInfo_H
#include <string>
#include "personType.h"
#include "dateType.h"
using namespace std;

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 = "",
int month = 1, int day = 1, int year = 1900, int ID = 0);
private:
personType name; // Composition
dateType bDay; // Composition
int personID;
};

#endif
46
#include <iostream>
#include <string>
#include "personalInfo.h"
using namespace std;

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;
}
personalInfo::personalInfo(string first, string last, int month,
int day, int year, int ID): name(first, last), bDay(month, day, year)
{
personID = ID;
} 47
#include <iostream>
#include "personalInfo.h"

using namespace std;

int main()
{
personalInfo newStudent("William", "Jordan", 8,24,1963,555238911);

newStudent.printpersonalInfo();

cout << endl;

return 0;
}

48
ObjectOrientedDesign(OOD)and
ObjectOrientedProgramming(OOP)
Thefundamentalprinciplesofobjectorienteddesign
(OOD)are:
Encapsulation:combinesdataandoperationsondataina
singleunit
Inheritance:createsnewobjects(classes)fromexisting
objects(classes)
Polymorphism:theabilitytousethesameexpressionto
denotedifferentoperations

C++ Programming: Program Design Including Data Structures, Sixth Edition 49


OODandOOP(contd.)
InOOD:
Objectisafundamentalentity
Debugattheclasslevel
Aprogramisacollectionofinteractingobjects
OODencouragescodereuse
Objectorientedprogramming(OOP)implements
OOD

C++ Programming: Program Design Including Data Structures, Sixth Edition 50


OODandOOP(contd.)
C++supportsOOPthroughtheuseofclasses
Functionnameandoperatorscanbeoverloaded
Polymorphicfunctionoroperator:hasmanyforms
Example:divisionwithfloatingpointanddivisionwith
integeroperands

C++ Programming: Program Design Including Data Structures, Sixth Edition 51


OODandOOP(contd.)
Templatesprovideparametricpolymorphism
C++providesvirtualfunctionstoimplement
polymorphisminaninheritancehierarchy
Allowsruntimeselectionofappropriatemember
functions
Objectsarecreatedwhenclassvariablesaredeclared
Objectsinteractwitheachotherviafunctioncalls

C++ Programming: Program Design Including Data Structures, Sixth Edition 52


OODandOOP(contd.)
Everyobjecthasaninternalstateandexternalstate
Private membersformtheinternal state
Public membersformtheexternal state
Onlytheobjectcanmanipulateitsinternalstate

C++ Programming: Program Design Including Data Structures, Sixth Edition 53


ProgrammingExample
Thisprogrammingexampleillustratestheconcepts
ofinheritanceandcomposition

Problem:Themidsemesterpointatyourlocal
universityisapproaching
Theregistrarsofficewantstopreparethegradereportsas
soonasthestudentsgradesarerecorded
ProgrammingExample(continued)
Someofthestudentsenrolledhavenotyetpaidtheir
tuition
Ifastudenthaspaidthetuition,thegradesareshownon
thegradereporttogetherwiththegradepointaverage
(GPA)
Ifastudenthasnotpaidthetuition,thegradesarenot
printed
Gradereportindicatesthatgradeshavebeenheldfor
nonpaymentofthetuition
Gradereportalsoshowsthebillingamount
TheDataFile
Dataarestoredinafileinthefollowingform:
15000345
studentName studentID isTuitionPaid numberOfCourses
courseName courseNumber creditHours grade
courseName courseNumber creditHours grade

studentName studentID isTuitionPaid numberOfCourses


courseName courseNumber creditHours grade
courseName courseNumber creditHours grade
TheDataFile(continued)
Thefirstlineindicatesnumberofstudentsenrolled
andtuitionratepercredithour
Studentsdataisgiventhereafter
Asampleinputfileis:
3345
LisaMiller890238Y4
MathematicsMTH3454A
PhysicsPHY3573B
ComputerSci CSC4783B
HistoryHIS3563A
..
Output
Sampleoutputforeachstudent:
StudentName:LisaMiller
StudentID:890238
Numberofcoursesenrolled:4
CourseNoCourseNameCreditsGrade
CSC478 ComputerSci 3 B
HIS356 History 3 A
MTH345 Mathematics 4 A
PHY357 Physics 3 B
Totalnumberofcredits:13
MidSemesterGPA:3.54
ProblemAnalysis
Twomaincomponentsare:
Course
Maincharacteristicsofacourseare:coursename,
coursenumber,andnumberofcredithours
Student
Maincharacteristicsofastudentare:studentname,
studentID,numberofcourses enrolled,namecourses,
andgrade foreachcourse

C++ Programming: Program Design Including Data Structures, Third Edition 59


ProblemAnalysis(continued)

Operationsonanobjectofthecoursetypeare:

1. Setthecourseinformation

2. Printthecourseinformation

3. Showthecredithours

4. Showthecoursenumber
AlgorithmDesign
Thebasicoperationstobeperformedonanobjectof
thetypestudentType:
1. Setstudentinformation
2. Printstudentinformation
3. Calculatenumberofcredithourstaken
4. CalculateGPA
5. Calculatebillingamount
6. Sortcoursesaccordingtocoursenumber
MainProgram
1. Declarevariables
2. Openinputfile
3. Ifinputfiledoesnotexist,exitprogram
4. Openoutputfile
5. Getnumberofstudentsregisteredandtuitionrate
6. Loadstudentsdata
7. Printgradereports
#ifndef H_courseType
#define H_courseType

#include <fstream>
#include <string>
using namespace std;

class courseType
{
public:
void setCourseInfo(string cName, string cNo, int credits);
void print(ofstream& outF);
int getCredits();
string getCourseNumber();
string getCourseName();
courseType(string cName = "", string cNo = "", int credits = 0);

private:
string courseName;
string courseNo;
int courseCredits;
};
#endif
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include "courseType.h"

using namespace std;

void courseType::setCourseInfo(string cName, string cNo, int credits)


{
courseName = cName;
courseNo = cNo;
courseCredits = credits;
}
void courseType::print(ostream& outF)
{
outF << left;
outF << setw(8) << courseNo << " ";
outF << setw(15) << courseName;
outF << right;
outF << setw(3) << courseCredits << " ;
}
courseType::courseType(string cName, string cNo, int credits)
{
courseName = cName;
courseNo = cNo;
courseCredits = credits;
}

int courseType::getCredits()
{
return courseCredits;
}

string courseType::getCourseNumber()
{
return courseNo;
}

string courseType::getCourseName()
{
return courseName;
}
#ifndef H_personType
#define H_personType

#include <string>

using namespace std;

class personType
{
public:
void print() const;
void setName(string first, string last);
string getFirstName() const;
string getLastName() const;
personType(string first = "", string last = "");

private:
string firstName;
string lastName;
};

#endif
#include <iostream>
#include <string>
#include "personType.h"
using namespace std;

void personType::print() const


{ cout << firstName << " " << lastName;
}
void personType::setName(string first, string last)
{ firstName = first;
lastName = last;
}
string personType::getFirstName() const
{ return firstName;
}
string personType::getLastName() const
{ return lastName;
}
personType::personType(string first, string last)

{ firstName = first;
lastName = last;
}
#ifndef H_studentType
#define H_studentType

#include <fstream>
#include <string>
#include "personType.h"
#include "courseType.h"

using namespace std;

class studentType: public personType // Inheritance


{
public:
void setInfo(string fname, string lName, int ID, int nOfCourses, bool isTPaid,
courseType courses[], char courseGrades[]);

void print(ostream& outF, double tuitionRate);


studentType();
int getHoursEnrolled();
double getGpa();
double billingAmount(double tuitionRate);
private:
void sortCourses(); // Private function, WHY? Will only be used
// internally by other member functions.
int sId;
int numberOfCourses;
bool isTuitionPaid;
courseType coursesEnrolled[6]; // Composition
char coursesGrade[6];
};

#endif
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include "personType.h"
#include "courseType.h"
#include "studentType.h"
using namespace std;

void studentType::setInfo(string fName, string lName, int ID,


int nOfCourses, bool isTPaid, courseType courses[], char cGrades[])
{ int i;
setName(fName, lName);
sId = ID;
isTuitionPaid = isTPaid;
numberOfCourses = nOfCourses ;

for (i = 0; i < numberOfCourses; i++)


{
coursesEnrolled[i] = courses[i];
coursesGrade[i] = cGrades[i];
}
sortCourses();
}
studentType::studentType()
{
// The constructors for the name and the courses enrolled will be
// automatically called to initialize the corresponding data members
numberOfCourses = 0;
sId = 0;
isTuitionPaid = false;
for (int i = 0; i < 6; i++)
coursesGrade[i] = '*';
}
int studentType::getHoursEnrolled()
{
int totalCredits = 0, i;
for (i = 0; i < numberOfCourses; i++)
totalCredits += coursesEnrolled[i].getCredits();

return totalCredits;
}
double studentType::billingAmount(double tuitionRate)
{
return tuitionRate * getHoursEnrolled();
}
void studentType::print(ostream& outF, double tuitionRate)
{
int i;
outF << "Student Name: " << getFirstName() << " " << getLastName() << endl;

outF << "Student ID: " << sId << endl;

outF << "Number of courses enrolled: " << numberOfCourses << endl;

outF << endl; outF << left;

outF << "Course No" << setw(15) << " Course Name"
<< setw(8) << "Credits" << setw(6) << "Grade" << endl;
outF << right;

for (i = 0; i < numberOfCourses; i++)


{ coursesEnrolled[i].print(outF);
if (isTuitionPaid)
outF <<setw(4) << coursesGrade[i] << endl;
else
outF << setw(4) << "***" << endl;
}
outF << endl;
outF << "Total number of credit hours: "<< getHoursEnrolled() << endl;

outF << fixed << showpoint << setprecision(2);

if (isTuitionPaid)
outF << "Mid-Semester GPA: " << getGpa() << endl;
else
{
outF << "*** Grades are being held for not paying the tuition. ***" << endl;

outF << "Amount Due: $" << billingAmount(tuitionRate) << endl;


}

outF << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-" << endl << endl;


}
double studentType::getGpa()
{ int i;
double sum = 0.0;

for (i = 0; i < numberOfCourses; i++)


{
switch (coursesGrade[i])
{
case 'A': sum += coursesEnrolled[i].getCredits() * 4;
break;
case 'B': sum += coursesEnrolled[i].getCredits() * 3;
break;
case 'C': sum += coursesEnrolled[i].getCredits() * 2;
break;
case 'D': sum += coursesEnrolled[i].getCredits() * 1;
break;
case 'F': sum += coursesEnrolled[i].getCredits() * 0;
break;
default: cout << "Invalid Course Grade." << endl;
}
}
return sum / getHoursEnrolled();
}
void studentType::sortCourses() // Selection Sort Algorithm on strings
{ int i, j, minIndex;
courseType temp;
char tempGrade;
string course1, course2;

for (i = 0; i < numberOfCourses - 1; i++)


{ minIndex = i;
for (j = i + 1; j < numberOfCourses; j++)
{
course1 = coursesEnrolled[minIndex].getCourseNumber();
course2 = coursesEnrolled[j].getCourseNumber();
if (course1 > course2)
minIndex = j;
}
temp = coursesEnrolled[minIndex];
coursesEnrolled[minIndex] = coursesEnrolled[i];
coursesEnrolled[i] = temp;
tempGrade = coursesGrade[minIndex];
coursesGrade[minIndex] = coursesGrade[i];
coursesGrade[i] = tempGrade;
}
}
#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, studentType studentList[],


int numberOfStudents, double tuitionRate);
int main()
{
studentType studentList[maxNumberOfStudents];

int noOfStudents;
double tuitionRate;
ifstream infile;
ofstream outfile;
infile.open("stData.txt");

if (!infile)
{
cout << "The input file does not exist. "
<< "Program terminates." << endl;
return 1;
}

outfile.open("sDataOut.txt");

infile >> noOfStudents;


infile >> tuitionRate;

getStudentData(infile, studentList, noOfStudents);

printGradeReports(outfile, studentList, noOfStudents, tuitionRate);

return 0;
}
void getStudentData(ifstream& infile, studentType studentList[],
int numberOfStudents)
{
string fName;
string lName;
int ID;
int noOfCourses;
char isPaid;
bool isTuitionPaid;

string cName;
string cNo;
int credits;

int count;
int i;

courseType courses[6];
char cGrades[6];
for (count = 0; count < numberOfStudents; count++)
{
infile >> fName >> lName >> ID >> isPaid;

if (isPaid == 'Y')
isTuitionPaid = true;
else
isTuitionPaid = false;

infile >> noOfCourses;

for (i = 0; i < noOfCourses; i++)


{
infile >> cName >> cNo >> credits >> cGrades[i];
courses[i].setCourseInfo(cName, cNo, credits);
}

studentList[count].setInfo(fName, lName, ID, noOfCourses, isTuitionPaid,


courses, cGrades);
}
}
void printGradeReports(ofstream& outfile, studentType studentList[],
int numberOfStudents, double tuitionRate)
{
int count;

for (count = 0; count < numberOfStudents; count++)


studentList[count].print(outfile, tuitionRate);
}
InputFile
3345
LisaMiller890238Y4
MathematicsMTH3454A
PhysicsPHY3573B
ComputerSci CSC4783B
HistoryHIS3563A

BillWilton798324N5
EnglishENG3783B
PhilosophyPHL5343A
ChemistryCHM2564C
BiologyBIO2344A
MathematicsMTH3463C

DandyGoat746333Y6
HistoryHIS1013A
EnglishENG3283B
MathematicsMTH1373A
ChemistryCHM3484B
ComputerSci CSC2013B
BusinessBUS1283C
OutputFile

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 credit hours: 13


Mid-Semester GPA: 3.54
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
OutputFile
Student Name: Bill Wilton
Student ID: 798324
Number of courses enrolled: 5

Course No Course Name Credits Grade


BIO234 Biology 4 ***
CHM256 Chemistry 4 ***
ENG378 English 3 ***
MTH346 Mathematics 3 ***
PHL534 Philosophy 3 ***

Total number of credit hours: 17


*** Grades are being held for not paying the tuition. ***
Amount Due: $5865.00
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
OutputFile
Student Name: Dandy Goat
Student ID: 746333
Number of courses enrolled: 6

Course No Course Name Credits Grade


BUS128 Business 3 C
CHM348 Chemistry 4 B
CSC201 ComputerSci 3 B
ENG328 English 3 B
HIS101 History 3 A
MTH137 Mathematics 3 A

Total number of credit hours: 19


Mid-Semester GPA: 3.16
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy