Title: Building Classes
1Building Classes
2Objectives
- See OCD applied where no predefined types exist
for objects - Learn how classes are designed, built
- Study encapsulation, information hiding
- Implement attributes as instance variables
- Describe roles of
- Constructors, accessors, mutators
- Converter and utility methods
- Illustrate a class to model temperatures
- See operator overloading (including I/O
operators) - An overview of artificial intelligence
3Introductory ExampleModeling Temperatures
- We seek a program that, given a temperature in
Fahrenheit, Celsius, or Kelvin will - Display the equivalent temperature
- In each of the scales
- We have two attributes
- Number of degrees
- The scale
- Operations would require both attributes to be
- Printed
- Read in
- Passed to functions
- etc.
This problem would be even worse for objects with
multiple attributes such as an IRS W-2 Form.
4Extending Object-Centered Design
- Previously we used OCD where an operation for an
object was not predefined.For each operation not
predefined - Define a function to perform the operation
- If reusable, store it in a library
- Also, we found that for an object with multiple
attributes we define a class - Now we combine those two concepts
- Declare class for multiple attributes
- Add methods to the class for needed operations
5Behavior
For temperature conversionEnter scale FEnter
temperature 99.9 Celsius equivalent
99.9Kelvin equivalent 99.9
6Objects
7Operations
- Display a string on the screen
- Read a Temperature from an istream
- Determine the Fahrenheit equivalent of a
Temperature - Determine the Celsius equivalent of a Temperature
- Determine the Kelvin equivalent of a Temperature
- Display a Temperature to an ostream
8Algorithm
- Via cout, display a prompt for a temperature
- From cin, read a temperature into theTemperature
- Via cout display
- The Fahrenheit equivalent of theTemperature
- The Celsius equivalent of theTemperature
- The Kelvin equivalent of theTemperature
- View source code, Figure 11.2
- Sample runs
9Designing a Class
- Two phases
- Design phase plan the class
- Implementation phase encode the design in C
language - Design is identifying
- Behavior the operations that can be applied to
a class object - Its attributes the data that must be stored to
characterize class objects
10External and Internal Principles
- External view
- An observer looking from outside the program at
its details - Internal perspective
- Object autonomy
- When you design a class, think of being the
object
11Temperature Behavior
- Define myself implicitly, default initial values
- Read a temp from an istream, store in my data
members - Compute Fahrenheit, Celsius, Kelvin equivalents
of me - Display my degrees and scale using an ostream
- Define myself explicitly, initializing with
specified values
12Temperature Behavior
- Identify my number of degrees
- Identify my scale
- Compute my temp raised/lowered by a given number
of degrees - Compare myself to other Temperature objects using
any of six relational operators - Assign another Temperature value to me using the
assignment operator
13Temperature Attributes
- Two data attributes
- My degrees
- My scale
- Implemented asdouble myDegreeschar myScale
// 'F', 'C', or 'K' only
14Encapsulation
- Wrap a class declaration around the
attributesclass Temperature public //
to be filled in later private double
myDegrees char myScale - We declare Temperature temp1, temp 2
15Information Hiding
- Preventing a program which uses a Temperature
object from directly accessing private
variablesclass Temperature public .
. . private double myDegrees
char myScale
User programs can access private attributes only
by using public methods.
16Class Invariants
- Restrictions placed on values of the instance
variables - We have specified myScale can only be'F', 'C',
or 'K' - We will also saymyScale 'F' myDegrees gt
-459.67 myScale 'C' myDegrees gt
-273.15 myScale 'K' myDegrees gt 0.0
17Conditional Compilation
- Preprocessor directivesinclude Filename
- If file is included by multiple files in a
program project, it can generate a duplicate
identifier error message - We specify another directiveifndef
TEMPERATUREdefine TEMPERATURE class
Temperature . . .endif
Then the actual class declaration is only
processed once by the compiler
18Temperature Output
- We want any Temperature object to be able to
print itselftemp1.print(cout) - Tells object temp1 to print itself, using cout
inline void Temperatureprint (ostream out)
const out ltlt myDegrees ltlt ' ' ltlt myScale
19The Default-Value Constructor
- When we declareTemperature temp1, temp 2
- We must assume "garbage" initial values
- We prefer to have a constructor which assigns
default values
20The Default-Value Constructor
- Constructor has the same name as the class.
- inline TemperatureTemperature()myDegrees
0.0myScale 'C' - A constructor has no return type
21Explicit Value Constructors
- The constructor must
- Receive potential values for the attributes
- Validate those values using the invariantsNote
isvalid() utility function, Figure 11.5 - Assign values to the attributes
- Constructor source code, Figure 11.6
- Now we can declare Temperature temp1 (98.6,
'F'), temp2What do the objects look like now?
22Accessor Methods
- Allows some attribute of the class to be read
- But not modified
- Programmer sends message to an object"Get your
degrees" temp1.getDegrees()inline double
TemperaturegetDegrees() const return
myDegrees
The getScale() method would be a similar
definition.
23Temperature Input
- We should be able to tell a Temperature object to
get attribute values from an istreamtemp2.read(ci
n) - The method should also validate the incoming
attributes - Will use isValid() utility method
- View the read() function, Figure 11.8
24Conversion Methods
- We need methods that enable a Temperature object
to return another Temperature object - With a new value for myScale
- With the appropriate value for myDegrees
- The method will
- Check the current scale
- Perform the proper mathematical conversion
- View source code, Figure 11.9
25Overloading Operators
- For some operations it is convenient to define an
operator for a class - We wish to be able to compare two Temperature
objectsif (temp1 lt temp2) - In general, we overload some operator with symbol
? by defining a method with the name operator?
26Overloading Operators
- What would complicate the following
comparison?Temperature(0,'C') lt
Temperature(32,'F') - Note source code, Figure 11.10
- Source code for operator, Figure 11.11
- Class declaration, Figure 11.12
The operatorlt method must account for the two
different scales!
?
27Case StudyRetrieving Student Information
- We need an information retrieval system for a
university registrar. - A data file contains lines of data in pairs of
lines - 1st line studentNumber firstName lastName
- 2nd line studentYear credits gradePointAverage
- The program must
- Allow the user to enter a student number
- Then retrieve and display information for that
student
28Objects
29Operations
- Read a sequence of students from the input file
- Display a prompt
- Read a long integer from keyboard
- Search a sequence of students for one with a
particular ID number - Compare two Student objects using lt
- Compare two Student objects using
- Display a student
- Repeat steps ii v an arbitrary number of times
30Algorithm
- Read a sequence of students from INPUT_FILE into
studentVec - Repeatedly do the following
- Prompt for and read studentID
- Search studentVec for a match, returning its
position - If search successful Display student at
position Otherwise Display an error message
31Building a Student Class
- Behaviors
- Initialize myself with default values
- Initialize myself with explicitly supplied values
- Read my attributes from an istream and store them
in me - Display my attributes using an ostream
- Compare myself and another Student using the lt
and the relational operators (also the other
relational operators for other applications) - Access any of my attributes
32Coding
- Note the class declaration in the header file,
Figure 11.13 - When we declare vectorltStudentgt studentVec
the effect can be visualized as follows
33Coding
- Partial implementation of the program (to be
finished by the student), Figure 11.14 - Input file, students.txt
- Sample run.
- Check your version of the program against what
you see here
34OBJECTive ThinkingOperator Overloading and
Friends
- Recall the print() and read() functions from
Temperature - Useful but don't fit with normal iostream
operators - Would be nice to use ltlt and gtgt
- Not possible to define operatorltlt as a member of
a class - object ? operand is interpreted
asobject.operator?(operand) - cout ltlt temp1 // temp1 is on wrong side
35Overloading
- We need to define a function which is not a class
member - operand ? operator is then interpreted
asoperator? (object, operand) - Now cout ltlt temp1 is interpreted asoperatorltlt
(cout, temp1) - Declarationinline ostream operatorltlt(ostream
out, const Temperature
theTemp) theTemp.print(out) return out
36Overloading
- The return out enables chaining of operatorltlt
callscout ltlt "The temp " ltlt temp1 ltlt endl
Value returned by this function call is a copy of
the ostream used in the call
37Using ltlt and gtgt
- Declaration of operatorgtgt which would call the
read() method is similar - Note temperature conversion program using the ltlt
and gtgt overloaded operators, Figure 11.19
38Friend Functions
- Consider the need to create an operatorltlt
function without the availability of a print()
function - What would be wrong?
inline ostream operatorltlt(ostream out,
const Temperature theTemp) out
ltlt theTemp.myDegrees ltlt ' ' ltlt
theTemp.myScale return out
39Friend Functions
- This can be made legal
- Place a prototype of the function in the class
declaration - Specify it as a friend function
- class Temperature public . . .
friend ostream operatorltlt (ostream
out, const Temperature theTemp) . . .
A similar friend declaration can be made for the
operatorgtgt function
40Artificial Intelligence
- Computers have successfully played chess against
skilled players - This is part of an area of computer science known
as artificial intelligence or AI - AI is an attempt to program computersto perform
intelligenttasks
41Artificial Intelligence
- A precise definition of artificial intelligence
is hard to do - Reasons
- Intelligent behavior is complex, hard to define
- Styles of programming used are diverse
- Check the website for the text
- Read Professor Vander Linden's introduction
- View some of the AI topics
- Try out code for a dice game called Not-One