Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software...

44
Using Classes Chapter 5

Transcript of Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software...

Page 1: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

Using Classes

Chapter 5

Page 2: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 2

Objectives

Further software development using OCD.

Introduce basic features of classes

Study I/O classes istream and ostream

Study the string class

Look at a user-defined random integer class

Take a first look at developing instance methods

Page 3: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 3

Intro Example

Consider displaying the song, "Farmer in the Dell"

The farmer in the dellThe farmer in the dellHi-Ho, the derry-oThe farmer in the dell

The farmer takes a wifeThe farmer takes a wifeHi-Ho, the derry-oThe farmer takes a wife

. . .

The farmer in the dellThe farmer in the dellHi-Ho, the derry-oThe farmer in the dell

The farmer takes a wifeThe farmer takes a wifeHi-Ho, the derry-oThe farmer takes a wife

. . .

Note the repetition.Note the repetition.

To print the song, we do NOT want a lot of cout lines, one for

each line of the song.

To print the song, we do NOT want a lot of cout lines, one for

each line of the song.

Page 4: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 4

Intro Example

Each verse is the same pattern• "The restOfLine" three times• "Hi-Ho, the derry-o" between 2nd and 3rd lines.

The farmer in the dellThe farmer in the dellHi-Ho, the derry-oThe farmer in the dell

The farmer takes a wifeThe farmer takes a wifeHi-Ho, the derry-oThe farmer takes a wife

. . .

The farmer in the dellThe farmer in the dellHi-Ho, the derry-oThe farmer in the dell

The farmer takes a wifeThe farmer takes a wifeHi-Ho, the derry-oThe farmer takes a wife

. . .

Desired Behavior:

Display on the screen the lyrics of a verse

Work through the verses

Page 5: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 5

Objects, Operations

Operations:

i. Display a string on the screen

ii. Construct a verse of the song using one of the constant strings

DescriptionSoftware Objects

Type Kind Namescreen ostream varying cout

lyrics of Farmer-in-the-Dell verse

string constant

"farmer in the dell" string constant

"farmer takes a wife" string constant

. . . string constant

Page 6: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 6

Algorithm

Note the "Construct a verse of the song using …"• Not predefined in C++• We design a function to perform the task

Then call that function 10 times• Once for each verse's phrase

Page 7: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 7

Function Behavior, Objects

Behavior• Receive phrase from caller for 1st, 2nd, 4th line of each verse• Construct verse• Return verse to calling function

Objects

DescriptionSoftware Objects

Type Kind Movement Name

screen ostream varying cout

a phrase string varying received (in) restOfLine

a verse of song string constant returned (out) aVerse

Page 8: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 8

Function Operations, Algorithm

Function Operationsi. Build aVerse consisting of lyric from

restOfLine in 1st, 2nd, 3rd lines

ii. Return aVerse to caller

Algorithm1. aVerse = "\nThe" + restOfLine+

"\nThe "+restOfLine+"\nHi-Ho, the derry-o"+"\nThe "+restOfLine.

2. Return aVerse

Page 9: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 9

Coding, Testing

View Source code, Figure 5.1Note:• Prototype• Call of function• Function definition

Note sample run of Figure 5.1

Page 10: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 10

Review of Classes

We can model many items by declaring variables, constants using predefined types

Other objects need multiple attributes declared

We encapsulate characteristics of an object within a single wrapper – a class

The characteristics are instance variables or data members or attribute variables of the class

Page 11: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 11

Class Objects

The name of a class is used to declare objects or instances of the class.Car dadsCar, momsCar;

Now all the attributes of a Car variable can be manipulated as a single entity• Send as a single parameter• Assign to another Car variable, etc.

Page 12: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 12

Encapsulating Operations

We can package more than data characteristics

We can package functions that make up• Operations• Messages to be sent to objects

These are called instance methods or function members• They perform specific operations using the

data members of the class

Page 13: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 13

Instance Methods

We send to an instance of the object, a message to do a task• dadsCar.print();• momsCar.read();

Also possible to redefine operators for classes• Redefine + for string objects• Redefine << or >> for Car objects• Called overloading a function or operator

Page 14: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 14

The istream Class

istream is a class which represents a flow of characters from an input device

cin is an object predefined from the istream library – a keyboard input stream

Page 15: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 15

The istream Class

The >> operator is defined in the istream class to extract a sequence of characters• int age;cin >> age;

• The operator is defined so as to interpret the characters according to the type of the variable

Page 16: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 16

The istream Class

One of the attributes of the class is a status value• If invalid values are entered for a given type

the status is set to a "fail" state

Functions provided to check the status

Message Returns True if and only if

cin.good() all is well with the istream

cin.bad() something is wrong with the istream

cin.fail() the last operation cold not be completed

Page 17: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 17

The istream Class

Functions provided to manipulate the status of stream flags

By default the >> operator skips leading white space• tabs• blanks• carriage returns

Message Action Taken

.clear()re-enables input operations for an istream object

.ignore() removes unwanted input from a stream

Page 18: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 18

The istream Class

Input manipulators• Identifiers which change some property of the istream

Example:cin >> … >> noskipws >> … ;

• Subsequent white space characters not skipped

Page 19: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 19

The ostream ClassThe iostream library provides the ostream class

ostream objects• cout standard stream for normal output display• cerr, clog standard output stream for displaying

errors and diagnostics

Page 20: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 20

The ostream Class

The << operator is defined in the ostream class to insert a sequence of characters into the stream

Exampleconst double PI = 3.1416;cout << PI;

Page 21: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 21

The ostream Class

Output manipulators• Identifiers that affects the ostream when used

in the output statementcout << "The answer = " << total << endl;

The endl is the same as a '\n' or a newline character• Causes output to be flushed from the ostream

Page 22: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 22

The ostream Class

Format control – use format manipulators• fixed used fixed point notation, reals• showpoint show decimal pt., trailing zeros• right right justify values, pad left• left left justify values, pad right

Example:cout << "\nTotal cost = $" << fixed << showpoint << cost << endl;

Note more extensive table of format manipulators on page 233

Page 23: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 23

The ostream Class

Format manipulators with arguments• setprecision(n) specify decimal digits• setw(n) specify width of field

These require#include <iomanip>

Examplecout << "\nTotal cost = $" << fixed << showpoint << setprecision(2) << cost << endl;

Page 24: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 24

string Objects

string is the name of a class• Thus it is a typestring lastName;

Used in a declaration• Creates a string object• Initializes it to an empty string

Other declarations(with initialization)string play = "Hamlet";

Page 25: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 25

string I/O

The string class has overloaded the<< and >> operators• Can do I/O directly with string objectsstring name, prompt = "Enter name : ";cout << prompt;cin >> name;

string input and whitespace• Skips leading whitespace characters• Quits reading when whitespace encountered

Page 26: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 26

Other string Operations

Subscript operation• Access individual characters of a stringstring name = "John Doe";cout << name [2];

Size method• Determine number

of characters in the stringcout << name.size();

Empty method• Returns true if string is empty

8 characters

Page 27: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 27

Other string Operations

Assignment operator• Assign values to string objectsstring yesterday, today = "Monday";

Relational operator• Elements of string operands compared

character by character

yesterday = today;today = "Tuesday"; string hisName = "James",

herName = "Jan";

How does hisName < herName evaluate? True or False?

How does hisName < herName evaluate? True or False?

Page 28: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 28

Other string Operations

Concatenation• Combining two strings into a single stringstring state = "Michigan", greatLake;greatLake = "Lake "+state;

The substr(first, num_chars) method• Returns a string from first for num_charscout << greatLake.substr(2,4);

What gets printed?What gets printed?

Page 29: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 29

Other string Operations

The replace(first, num_chars, replace) method• Replaces the contents of the replace string

starting at first, for num_chars• Given

• What is the end result offullname.replace(5,6,"Eyre");

Six characters replaced with four.

Six characters replaced with four.

Page 30: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 30

Other string Operations

The insert(position, new_string) method• Inserts a substring into a string• Given

• What is the result ofsignature.insert (5,"E. ");

Page 31: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 31

Other string Operations

The find(pattern, position) and rfind(pattern, position) methods• These do pattern matching • Searches for the specified pattern starting at the given

position• Returns the index of where it is found (returns value of string::npos if not found)

• rfind searches from right to left

The find_first_of(pattern, position)method• Looks for first character from any in pattern starting

at position

Page 32: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

Problem Session

Working in groups of two,

solve the following problem...

Page 33: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 33

Problem

Using OCD, design and implement a function that, • Given a string containing a long-distance

telephone number, • Decomposes that number into its

• Area code (if the first number is a 1) • Exchange • Local number.

Only these two if the first number is not a 1

Only these two if the first number is not a 1

Page 34: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 34

Behavior

Enter Phone number -> 12345556789

This is a valid number.Area code : 234Exchange : 555Local No. : 6789

Page 35: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 35

Objects

Use description to fill in chart for objects.

DescriptionSoftware Objects

Type Kind Name

Page 36: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 36

Operations

i.

ii.

iii.

iv.

v.

vi.

See complete solution at text web site.

Page 37: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 37

Part of the Picture : SimulationSimulation• Modeling a dynamic process• Using the model to study process behavior• Some deterministic processes can be modeled

with equations

Example: Exponential growth modeled by

0( ) ktA t A e

Page 38: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 38

Simulation

Many problems modeled using randomness

Requires a random number generator subprogram• Technically can be only pseudo-random

Properties• Initial seed value required to begin process• Each random number used to compute next

Page 39: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 39

RandomInt Class

Operations provided• Construction – initialized object with a random

number• Generation – provides object with new random

number

ConstructorRandomInt object_name (low, high);

Generate a new random numberobject_name.generate();

Page 40: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 40

Modeling a Dice Roll

To model roll of two dice• Declare two objectsRandomInt die1 (1,6), die2(1,6);

• Generate random valuesdie1.generate(); die2.generate();

• Add the two values for the rollint pair = die1 + die2;

Note implementation Figure 5.2

View sample run

Page 41: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 41

Normal Distributions

Normal distributions model many physical processes

Note familiar bell shaped curve

Page 42: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 42

Normal Distributions

Algorithm to generate standard normal distribution1. Set sum = 02. Do the following 12 times

1. Generate random number, x from uniform distribution

2. Add x to sum3. Calculate z = sum – 64. To generate random number y with mean μ

and standard deviation σ, calculate

y z

Page 43: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 43

OBJECTive Thinking:Instance Methods

Review of class methodsAccessor method – instance method which retrieves value of instance variableMutator method – instance method that modifies value of instance variableConverter – instance method which returns different representation/type of objectUtility – instance method used by other methods (avoids redundant coding)

Page 44: Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

C++ An Introduction to Computing, 3rd ed. 44

Accessor Methods

Sample accessors for class Name• Figure 5.3• Driver Figure 5.4

Sample accessors for class Student• Figure 5.5• Driver Figure 5.6