Title: Class Operations
1Class Operations
Creating New Types
2Review
- Last time, we began building Temperature, a class
to allow us to model temperatures
class Temperature public Temperature()
Temperature(double magnitude, char
scale) Temperature TemperatureCelsius()
const void Read(istream in) void
Print(ostream out) const private double
myMagnitude char myScale
3- Temperature TemperatureCelsius() const
-
- switch (myScale)
-
- case 'C'
- return Temperature(myMagnitude, 'C')
- case 'F'
- return Temperature((myMagnitude - 32)/1.8,
'C') - default
- cerr ltlt "\nInvalid scale " ltlt myScale
- ltlt " in Celsius().\n" ltlt endl
- exit(1)
-
4Review
- We saw that classes have
- data members, for storing class attributes and
- function members, for operating on class objects.
- Function members are like messages sent to an
object -- when an object receives a message,
that object performs the statements in the
functions definition.
5Fahrenheit() Definition
The Fahrenheit() definition and prototype are
similar to those of Celsius()
Temperature TemperatureFahrenheit() const
switch (myScale) case F return
Temperature(myMagnitude, F) case C
return Temperature(myMagnitude 1.8 32, F)
default cerr ltlt \nInvalid scale ltlt
myScale ltlt in Fahrenheit().\n ltlt
endl exit(1)
6Fahrenheit() Prototype
class Temperature public Temperature()
Temperature(double magnitude, char scale)
Temperature Celsius() const Temperature
Fahrenheit() const void Read(istream in)
void Print(ostream out) const private
double myMagnitude char myScale
7Accessor Functions
- To find out the magnitude or scale of a
temperature object, we want to be able to send it
the Magnitude() or Scale() messages.
Temperature temp1 // ... cout ltlt Its
magnitude is ltlt temp1.Magnitude()
ltlt and its scale is ltlt temp1.Scale()
ltlt endl
Such functions are called accessor functions,
since they access (retrieve) the values of data
members.
8Accessor Prototypes
class Temperature public Temperature()
Temperature(double magnitude, char scale)
double Magnitude() const char Scale() const
Temperature Celsius() const void Read(istream
in) void Print(ostream out) const
private double myMagnitude char myScale
Why are these declared as const functions?
9Accessor Definitions
The Scale() and Magnitude() functions are similar
char TemperatureScale() const return
myScale
double TemperatureMagnitude() const return
myMagnitude
10Accessor Definitions
The Scale() and Magnitude() functions are similar
inline char TemperatureScale() const return
myScale
inline double TemperatureMagnitude() const
return myMagnitude
- Functions this simple can be defined in the
header file, provided they are declared as inline
functions, which - eliminates function-call overhead and
- eliminates multiple-definition linking errors.
11Main() function
- include "Temperature.h"
- int main()
-
- cout ltlt "\nEnter a temperature "
- Temperature temp1, temp2
- temp1.Read(cin) // read
- temp1.Print(cout)
- cout ltlt endl
- if (temp1.Scale()'F')
- temp2 temp1.Celsius() // convert
- else
- temp2 temp1.Fahrenheit() // convert
- temp2.Print(cout) // output
- cout ltlt endl
- cout ltlt temp1.Magnitude()ltlt" "
ltlttemp1.Scale()ltltendl - cout ltlt temp2.Magnitude()ltlt" "
ltlttemp2.Scale()ltltendl - cout ltlt endl
12Practice Building Classes
Modeling Objects
13Problem
- Write a program that computes the Deans List
(full-time students whose GPA ³ 3.0), using a
student data file. - Each student-record in the file consists of three
lines - 12345
- Jane Doe
- 3.35 14
- representing student Jane Doe, with student id
12345, with GPA 3.35 and 14 credit hrs this
semester.
14Behavior
- Our program should prompt for and read the name
of the data file from the user. It should then
open an ifstream to that file. It should then
prompt for and read the name of an output file
and open an ofstream to that file. Using an
input loop, our program should read in the
sequence of students. It should then process
this sequence by printing to the ofstream each
full-time student whose GPA is 3.0 or greater.
15Objects
- Description Type Kind Name
in-file name string varying inFileName
out-file name string varying outFileName
input fstream ifstream varying fin
output fstream ofstream varying fout
students vectorltStudentgt varying students
GPA double varying studentsi.GPA()
16Operations
- Description Predefined? Library?
Name
display a string yes string ltlt
read a string yes string gtgt
open/close fstreams yes fstream --
read students in an ?? -- for, if
input loop break
identify Deans List ?? -- for, if
students , ??
output a student ?? -- ??
17Algorithm
- 0. Display purpose of program
- 1. Prompt for and read name of input file from
cin into inFileName. - 2. Open fin to inFileName, fout to outFileName,
verify opens. - 3. Read sequence of students from fin into
students, using an input loop. - 4. Close fin.
- 5. Prompt for and read name of output file from
cin into outFileName. - 6. Write students qualifying for the Deans List
to fout. - 7. Close fout.
- 8. Display a processing completed message via
cout.
18OCD with Classes
- 0. Specify the behavior of the program.
- 1. Identify the objects in the behavior.
- 1a. If an object cannot be modeled with
available types, - declare a class by which such objects can be
modeled. - 2. Identify the operations in the behavior.
- 2a. If an operation is not predefined,
- build a function to perform that operation.
- 2b. If the left operand of an operation is a
class object, - make the operation a function member of the
class. - 3. Organize your objects and operations into an
algorithm.
19A Student Class
- Begin by defining variables to store the
attributes of the object being represented (a
student) in a class header file (e.g., Student.h)
int myID string myName double myGPA int
myCredits
Clearly, it would be easy to add other data
members (academic year, address, ...) as
necessary.
20Building Classes
- We then wrap these variables in a class
declaration
class Student public private int myID
string myName double myGPA int myCredits
21Prototypes
class Student public Student() Student(int
id, const string Name, double gpa,
int credits) int ID() const string Name()
const double GPA() const int Credits()
const void Read(istream in) void
Print(ostream in) private int myId string
myName double myGPA int myCredits
22Operation Default Constructor
- The default constructor initializes the data
members to default values
Student aStudent
Specification Postcondition myid 0 myName
myGPA 0.0
myCredits 0.
23Default Constructor
This is sufficiently simple to define inline in
Student.h
inline StudentStudent() myID 0 myName
myGPA 0.0 myCredits 0
24OperationExplicit-Value Constructor
This constructor lets you initialize the data
members to specified values
Student aStudent(12345, Jane Doe,
3.35, 14)
- Specification
- Receive id, an int name, a string gpa, a
double, and - credits, an int.
- Precondition id is a valid id, gpa is a valid
gpa, and - credits is a valid number of
credits. - Postcondition myid id myName name
- myGPA gpa myCredits
credits.
25Explicit-Value Constructor
This is sufficiently complicated to define in
Student.cpp
// ... include Student.h StudentStudent(int
id, const string name, double
gpa, int credits) assert(id gt 0 gpa gt 0.0
gpa lt 4.0 credits gt 0
credits lt 21) myID id myName name
myGPA gpa myCredits credits
26Operation Print()
- The Print() function retrieves data member values
cout ltlt aStudent.ID() ltlt aStudent.Name()
ltlt aStudent.GPA() ltlt
aStudent.Credits()
Specifications ID Return myID. Name Return
myName. GPA Return myGPA. Credits Return
myCredits.
27Default Constructor
These are sufficiently simple to define inline in
Student.h
inline int StudentID() const return myID
inline string StudentName() const return
myName
inline double StudentGPA() const return
myGPA
inline int StudentCredits() const return
myCredits
28OperationInput Read()
The Read() function lets you read Student values
aStudent.Read(cin)
- Specification
- Receive in, an istream stu, a Student.
- Precondition in contains a valid Student value.
- Input the Student value from in.
- Passback
- Return
29Input function
This is sufficiently complicated to define in
Student.cpp. Its form is dictated by the
record-format in the data file
// ... Void Read(istream in) in gtgt myID
// read id on one line char ch
in.get(ch) // eat the newline
getline(in, myName) // read name (2 words) in
gtgt myGPA // read GPA gtgt myCredits
// read credits
30OperationOutput Print()
The Print() lets you write Student values
aStudent.Print(cout) cout ltlt endl
- Specification
- Receive out, an ostream
- Output stus Student value, via out.
- Passback
- Return
31Output function
This is sufficiently complicated to define in
Student.cpp. We will use a format consistent with
that in the data file
// ... Void Print(ostream out) out ltltmyID
ltlt \n // put id on one line ltltmyName ltlt
\n // put name ltltmyGPA ltlt // put
GPA ltltmyCredits // put credits
return out // allow chaining
32Coding Our Algorithm
- We are now ready to implement our algorithm...
// deansList.cpp // ... documentation // ...
other includes include Student.h int
main() cout ltlt \nTo generate the Deans
List, ltlt \n enter the input file name
string inFileName cin gtgt inFileName
ifstream fin(inFileName.data())
assert(fin.is_open())
33Coding (Ctd)
// ... deansList.cpp continued Student
aStudent vectorltStudentgt students for ()
aStudent.Read(fin) assert(aStudent.ID() gt 0
aStudent.GPA() gt 0.0 aStudent.GPA() lt 4.0
aStudent.Credits() gt 0
aStudent.Credits() lt 21) students.push_back(a
Student) if (fin.eof()) break
fin.close() // ...
34Coding (Ctd)
// ... deansList.cpp continued cout ltlt
\nEnter the output file name string
outFileName cin gtgt outFileName ofstream
fout(outFileName.data()) assert(fout.is_open())
for (unsigned i 0 i lt students.size()
i) if (studentsi.GPA() gt 3.0
studentsi.Credits() gt 12) studentsi.Print(f
out) fout ltlt \n\n fout.close()
cout ltlt \nProcessing complete. Results are in
ltlt outFileName ltlt endl
35Summary
- C classes enable a programmer to define new
types that provide rich sets of operations. - Function members that do not modify class data
members should be declared as const functions. - Trivial function members can be defined in the
header file, so long as they are declared as
inline functions. - A class can grant non-function-members access to
the private data by naming them as friends of the
class.
36Summary
- C classes allow real world objects to be
modeled in software. - Classes are objects, and can be stored in
containers, such as the STL vector. - Most classes require at least
- a default-value constructor
- an explicit-value constructor
- extractor functions
- I/O functions