Chapter11 230 PDF
Chapter11 230 PDF
Chapter11 230 PDF
InheritanceandComposition
Objectives
Inthischapter,youwill:
Learnaboutinheritance
Learnaboutderivedandbaseclasses
Redefinethememberfunctionsofabaseclass
Examinehowtheconstructorsofbaseandderivedclasses
work
Learnhowtoconstructtheheaderfileofaderivedclass
o memberAccessSpecifier ispublic,protected,
orprivate (default)
private membersofabaseclassareprivate to
thebaseclass
o Derivedclasscannotdirectly accessthem
private:
double length;
double width;
};
boxType();
private:
double height;
};
17
#include <iostream>
#include "rectangleType.h"
#include "boxType.h"
if (h >= 0)
height = h;
else
height = 0;
}
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
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 << "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
#endif
27
Multiple Inclusions of a Header
File
Problem: Solution:
28
C++StreamClasses
ios isthebaseclassforallstreamclasses
Containsformattingflagsandmemberfunctionsto
access/modifytheflagsettings
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
class bClass
{
public:
void setData(double);
void setData(char, double);
void print() const;
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;
}
#include "protectMembClass.h"
private:
int dA;
};
#endif
37
#include <iostream>
#include "protectMembClass.h"
#include "protectMembInDerivedCl.h"
dA = a;
}
38
#include <iostream>
#include "protectMembClass.h"
#include "protectMembInDerivedCl.h"
int main()
{
bClass bObject;
dClass dObject;
bObject.print();
cout << endl; // Base class: bCh = *, bX = 0
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;
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;
int main()
{
personalInfo newStudent("William", "Jordan", 8,24,1963,555238911);
newStudent.printpersonalInfo();
return 0;
}
48
ObjectOrientedDesign(OOD)and
ObjectOrientedProgramming(OOP)
Thefundamentalprinciplesofobjectorienteddesign
(OOD)are:
Encapsulation:combinesdataandoperationsondataina
singleunit
Inheritance:createsnewobjects(classes)fromexisting
objects(classes)
Polymorphism:theabilitytousethesameexpressionto
denotedifferentoperations
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
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"
int courseType::getCredits()
{
return courseCredits;
}
string courseType::getCourseNumber()
{
return courseNo;
}
string courseType::getCourseName()
{
return courseName;
}
#ifndef H_personType
#define H_personType
#include <string>
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;
{ firstName = first;
lastName = last;
}
#ifndef H_studentType
#define H_studentType
#include <fstream>
#include <string>
#include "personType.h"
#include "courseType.h"
#endif
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include "personType.h"
#include "courseType.h"
#include "studentType.h"
using namespace std;
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 << "Number of courses enrolled: " << numberOfCourses << endl;
outF << "Course No" << setw(15) << " Course Name"
<< setw(8) << "Credits" << setw(6) << "Grade" << endl;
outF << right;
if (isTuitionPaid)
outF << "Mid-Semester GPA: " << getGpa() << endl;
else
{
outF << "*** Grades are being held for not paying the tuition. ***" << endl;
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");
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;
BillWilton798324N5
EnglishENG3783B
PhilosophyPHL5343A
ChemistryCHM2564C
BiologyBIO2344A
MathematicsMTH3463C
DandyGoat746333Y6
HistoryHIS1013A
EnglishENG3283B
MathematicsMTH1373A
ChemistryCHM3484B
ComputerSci CSC2013B
BusinessBUS1283C
OutputFile