4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer...

31
4-1 Computing Fundamentals Computing Fundamentals with C++ with C++ Object-Oriented Programming and Design, Object-Oriented Programming and Design, 2nd Edition 2nd Edition Rick Mercer Rick Mercer Franklin, Beedle & Associates, 1999 Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8 ISBN 1-887902-36-8 Presentation Copyright 1999, Franklin, Beedle & Associates Presentation Copyright 1999, Franklin, Beedle & Associates Students who purchase and instructors who adopt Students who purchase and instructors who adopt Computing Computing Fundamentals with C++, Object-Oriented Programming and Design Fundamentals with C++, Object-Oriented Programming and Design by Rick Mercer by Rick Mercer are welcome to use this presentation as long as this copyright are welcome to use this presentation as long as this copyright notice remains intact. notice remains intact.

Transcript of 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer...

Page 1: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-1

Computing Fundamentals with C++Computing Fundamentals with C++Object-Oriented Programming and Design, 2nd EditionObject-Oriented Programming and Design, 2nd Edition

Rick MercerRick Mercer

Franklin, Beedle & Associates, 1999Franklin, Beedle & Associates, 1999

ISBN 1-887902-36-8ISBN 1-887902-36-8

Presentation Copyright 1999, Franklin, Beedle & Associates Presentation Copyright 1999, Franklin, Beedle & Associates Students who purchase and instructors who adopt Students who purchase and instructors who adopt Computing Fundamentals with C++, Computing Fundamentals with C++, Object-Oriented Programming and Design Object-Oriented Programming and Design by Rick Mercer are welcome to use this by Rick Mercer are welcome to use this

presentation as long as this copyright notice remains intact.presentation as long as this copyright notice remains intact.

Page 2: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-2 Chapter 4Chapter 4Messages and Member FunctionsMessages and Member Functions

Chapter ObjectivesChapter Objectives Send messages to objectsSend messages to objects Understand how to send a few string and ostream Understand how to send a few string and ostream

messages and the effect they have on the object messages and the effect they have on the object Problem solve with grid and bankAccount objectsProblem solve with grid and bankAccount objects Appreciate why programmers partition software into Appreciate why programmers partition software into

classes, which are a collection of member functions classes, which are a collection of member functions combined with related datacombined with related data

– Exercises and Programming Projects to reinforce sending Exercises and Programming Projects to reinforce sending messages to standard classes and some author-supplied classesmessages to standard classes and some author-supplied classes

Page 3: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-3 Find the objects in hereFind the objects in here

Problem:Problem: Implement a bank teller application to Implement a bank teller application to allow bank customers to access bank accounts allow bank customers to access bank accounts through an identification number. The customer, through an identification number. The customer, with the help of the teller, may complete any of the with the help of the teller, may complete any of the following transactions: withdraw money, deposit following transactions: withdraw money, deposit money, query account balances, and view any and money, query account balances, and view any and all transactions between any two given dates. The all transactions between any two given dates. The system must maintain the correct balances for all system must maintain the correct balances for all accounts and produce monthly statements.accounts and produce monthly statements.

Page 4: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-4 Nouns are possible classesNouns are possible classes

Potential Classes to Model a Solution:Potential Classes to Model a Solution: tellerteller customercustomer bank accountbank account identification numberidentification number transactiontransaction list of transactionslist of transactions datedate monthly statementmonthly statement

Page 5: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-5 4.1.1 class 4.1.1 class bankAccountbankAccount

bankAccount represents a simple checking or savings bankAccount represents a simple checking or savings account.account.

Operations:Operations:withdrawwithdrawdepositdepositbalance balance // return account balance// return account balancename name // return account name// return account name

State is represented byState is represented bystring my_name;string my_name;double my_balance;double my_balance;

Initialization requires Initialization requires twotwo arguments argumentsbankAccount anAcct("Kelsey Jenkins", 250.00); bankAccount anAcct("Kelsey Jenkins", 250.00);

Page 6: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-6Some objects need 2 or more Some objects need 2 or more arguments in the constructorarguments in the constructor

ints, doubles, and strings could be initialized with ints, doubles, and strings could be initialized with only one argument:only one argument:

// Equivalent initialization with ( )// Equivalent initialization with ( ) int n = 0; int n = 0; // int n(0);// int n(0); double x = 0.000001; double x = 0.000001; // double x(0.0);// double x(0.0); string s = "A string"; string s = "A string"; // string s("A string");// string s("A string");

bankAccount objects require twobankAccount objects require two Initialization with = is not an option Initialization with = is not an option

bankAccount anAccount("Gosch", 100.00);bankAccount anAccount("Gosch", 100.00);

Page 7: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-7 MessagesMessages

Some messages return the object's state. Other Some messages return the object's state. Other messages tell an object to do something:messages tell an object to do something:

A A messagemessage that asks the object to return its state: that asks the object to return its state: cout << anAccount.balance() << endl;cout << anAccount.balance() << endl;

A A message message that tells the object to do something:that tells the object to do something: anAccount.withdraw(25.00);anAccount.withdraw(25.00);

Page 8: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-8 Messages Messages continuedcontinued

General Form: General Form: sending a message to an objectsending a message to an object

object-name object-name .. function-namefunction-name((argument-listargument-list))

ExamplesExamples anAccount.deposit(100.00);anAccount.deposit(100.00); cout.width(6);cout.width(6); cout << anAccount.balance() << endl;cout << anAccount.balance() << endl; cout << aString.length() << endl;cout << aString.length() << endl; aGrid.move(3);aGrid.move(3);

Page 9: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-9 Example ProgramExample Program

// Initialize 2 bankAccount objects, send some messages // Initialize 2 bankAccount objects, send some messages #include "baccount" #include "baccount" // for class bankAccount// for class bankAccount #include <iostream>#include <iostream>using namespace std;using namespace std;

int main()int main(){{ bankAccount one("Stoers", 200.00);bankAccount one("Stoers", 200.00); bankAccount two("Daly", 125.00);bankAccount two("Daly", 125.00); // assert: anAcct and anotherAcct are initialized// assert: anAcct and anotherAcct are initialized one.deposit(133.33);one.deposit(133.33); two.withdraw(50.00);two.withdraw(50.00); cout << one.name() << ": " << one.balance() << endl;cout << one.name() << ": " << one.balance() << endl; cout << two.name() << ": " << two.balance() << endl;cout << two.name() << ": " << two.balance() << endl; return 0;return 0;}}

Program Output?Program Output?Optional Demo accounts2.cpp

Page 10: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-10 4.1.3 Class and Object Diagrams4.1.3 Class and Object Diagrams

Relationship between a class and it objects Relationship between a class and it objects using the using the Unified Modeling Language diagramUnified Modeling Language diagram

Page 11: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-11 String messages String messages and two new operatorsand two new operators

Some objects have so many operations, we resort to Some objects have so many operations, we resort to using descriptive operation using descriptive operation namesnames

The The [][] operator returns a single character in a string. operator returns a single character in a string. The The ++ operator concatenates two strings operator concatenates two strings

However, which operator shouldHowever, which operator should return the dynamic length of a string object?return the dynamic length of a string object? return the beginning location of a string in another? return the beginning location of a string in another? return a portion of a string object (a substring)return a portion of a string object (a substring)

Answers: The operations namedAnswers: The operations namedlength find substrlength find substr

Page 12: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-12 Some string operations Some string operations

string aString("Any old string") ;string aString("Any old string") ;// assert: aString is initialized// assert: aString is initialized

cout << aString[0] << endl ;cout << aString[0] << endl ;// assert: A has been output (C++ startd counting at 0)// assert: A has been output (C++ startd counting at 0)

cout << aString[1] << endl ;cout << aString[1] << endl ;// assert: n has been output (C++ starts counting at 0)// assert: n has been output (C++ starts counting at 0)

cout << aString.length() << endl ;cout << aString.length() << endl ;// assert: aString.length() returns 14// assert: aString.length() returns 14

cout << aString.find("ring") << endl ;cout << aString.find("ring") << endl ;// assert: aString.find("ring") returns 10// assert: aString.find("ring") returns 10

cout << aString.substr(4, 7) << endl ;cout << aString.substr(4, 7) << endl ;// assert: returns "old str",// assert: returns "old str", aString[4]..aString[11]aString[4]..aString[11]

Page 13: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-13 4.2.2 ostream and istream 4.2.2 ostream and istream Member FunctionsMember Functions

Other standard C++ classes and named operations Other standard C++ classes and named operations include: include:

ostream::ostream:: widthwidth, , precisionprecision, , setfsetf istream::istream:: goodgood,, bad bad, , clearclear string::string:: replacereplace, , c_strc_str vector::vector:: capacitycapacity,, resize resize

Demonstrate strings with p115.cpp

Page 14: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-14ostream::width and ostream::width and ostream::precisionostream::precision

#include <iostream> #include <iostream> // for cout // for cout using namespace std;using namespace std; int main()int main() {{ double x = 9.87654321;double x = 9.87654321; cout << "123456789" << endl;cout << "123456789" << endl; cout.precision(4);cout.precision(4); cout.width(9);cout.width(9); cout << x << endl;cout << x << endl; cout.precision(3);cout.precision(3); cout.width(8);cout.width(8); cout << x << endl;cout << x << endl; return 0;return 0; }}

Output:

123456789123456789 9.8779.877 9.889.88

Page 15: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-154.2.4 Class Member Function 4.2.4 Class Member Function HeadingsHeadings

Member function names are distinguished Member function names are distinguished from non-member functions by qualifying the from non-member functions by qualifying the operation with the class-name and operation with the class-name and :::: (the (the scope resolution operator)scope resolution operator)

Example function names as you might see them Example function names as you might see them referred to in the textreferred to in the textostream::widthostream::widthistream::goodistream::goodstring::lengthstring::lengthstring::substrstring::substr

Page 16: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-16 Class member function headingsClass member function headings

Member function headings are also qualifiedMember function headings are also qualified Here are the member functions used so far:Here are the member functions used so far: int string::length()int string::length()

int string::find(string subString)int string::find(string subString)

string string::substr(int pos, int n)string string::substr(int pos, int n)

int ostream::width(int nCols)int ostream::width(int nCols)

int ostream::precision(int nDigits)int ostream::precision(int nDigits)

int istream::good()int istream::good()

Page 17: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-17 Why qualify member function headings?Why qualify member function headings?

The previous class member function headings The previous class member function headings indicate the class to which the function belongsindicate the class to which the function belongs

You will be required to use the qualification to You will be required to use the qualification to implement class member functions if you study implement class member functions if you study Chapter 6Chapter 6

Page 18: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-18 Differences between member and Differences between member and non-member functionsnon-member functions

Page 19: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-19 4.3 Another nonstandard class4.3 Another nonstandard class gridgrid

A A grid grid object object stores a little rectangular map made up of rows and stores a little rectangular map made up of rows and

columnscolumns has an object to move around. has an object to move around. is initialized with five arguments:is initialized with five arguments:

grid grid-name(rows, cols, moverRow, moverCol, direction);

where the first four arguments are integers and where the first four arguments are integers and directiondirection is either is either northnorth, , southsouth, , easteast, or , or westwest

Page 20: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-20 ExampleExample

#include "grid" // for class grid

int main(){ grid aGrid(5, 10, 0, 0, east); aGrid.display();}Program Output:

The grid:> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Page 21: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-21 One grid ConstructorOne grid Constructor

Use this class member function heading to help Use this class member function heading to help understand the construction of a grid object:understand the construction of a grid object:

grid::grid(int Rows, int Cols, int startRow, int startCol, int direction) // post: construct a 10 by 10 grid object with 5 arguments 1

grid aGrid(10, 10, 0, 0, east);

Page 22: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-22Accessing the state of a grid Accessing the state of a grid objectobject

We observe state of grid objects with We observe state of grid objects with grid::display grid::display constconst means means displaydisplay does not modify the objectdoes not modify the object

void grid::display() const // post: The current state of the grid is // post: The current state of the grid is displayed on the computer screendisplayed on the computer screen

Also access the state of grid objects with Also access the state of grid objects with grid::row grid::row // the row the mover is in// the row the mover is in grid::column grid::column // the column the mover is in// the column the mover is in grid::nRows grid::nRows // the maximum number of rows// the maximum number of rows grid::nColumns grid::nColumns // the maximum number of rows// the maximum number of rows

Page 23: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-23 Member functions that modify the state Member functions that modify the state of a grid objectof a grid object

void grid::move(int nSpaces)// pre: The mover has no obstructions in the next nSpaces // pre: The mover has no obstructions in the next nSpaces // post: the mover has moved nSpaces forward// post: the mover has moved nSpaces forward

void grid::putDown(int putDownRow, int putDownCol)// pre: The intersection (putDownRow, putDownCol) has nothing// pre: The intersection (putDownRow, putDownCol) has nothing// on it expect perhaps the mover// on it expect perhaps the mover// post: There is one thing at the intersection // post: There is one thing at the intersection

void grid::pickUp()// pre: There is something to pickup at the movers location// pre: There is something to pickup at the movers location// post: There is nothing to pick up// post: There is nothing to pick up

void grid::turnLeft()// post: The mover is facing 90 degrees counter-clockwise// post: The mover is facing 90 degrees counter-clockwise

void grid::block(int blockRow, int blockCol)// pre: There is nothing at all at the intersection// pre: There is nothing at all at the intersection// post: The intersection can no longer be used// post: The intersection can no longer be used

Page 24: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-24 4.3.2 Failing to Meet the Preconditions4.3.2 Failing to Meet the Preconditions

There are many "illegal" messages you can There are many "illegal" messages you can send to a grid object. For examplesend to a grid object. For example

send a message telling the mover to move send a message telling the mover to move through a block ('#')through a block ('#')

send a message telling the mover to move off the send a message telling the mover to move off the edge of the worldedge of the world

List some other sensible preconditionsList some other sensible preconditions

Demonstrate grid with p125.cpp

Page 25: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-25 So what are we to do?So what are we to do?

A precondition is a statement the client A precondition is a statement the client must ensure is true before sending a must ensure is true before sending a messagemessage

If the client ignores it, the resulting If the client ignores it, the resulting behavior is undefined--tough luckbehavior is undefined--tough luck

You can experiment and see what You can experiment and see what happens when you run programs with grid happens when you run programs with grid objectsobjects

Page 26: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-264.3.3 Functions with no 4.3.3 Functions with no Arguments still need Arguments still need ( )( )

Note: Remember to include Note: Remember to include ( )( ) even when even when no arguments are required in a message:no arguments are required in a message:

cout << aString.length << endl; // ERROR: Missing () after length// ERROR: Missing () after length

cout << aGrid.row << endl; // ERROR: Missing () after row// ERROR: Missing () after row

Page 27: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-274.5 Why Functions and 4.5 Why Functions and Classes?Classes?

AbstractionAbstraction has many meaningshas many meanings is the process of pulling out and highlighting the is the process of pulling out and highlighting the

relevant features of a complex systemrelevant features of a complex system allows us to use existing functions and classes allows us to use existing functions and classes

more easilymore easily allows us to use existing software without allows us to use existing software without

knowing all the implementation details knowing all the implementation details how it workshow it works

Page 28: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-28 Functions hide a lot of detailFunctions hide a lot of detail

One function call can represent many statements One function call can represent many statements (or lines of code)(or lines of code)

Operation The object-oriented way With thedetails

Construct one gridobject

grid g(15,15,9,4,east) ; 35 lines

Move in currentdirection

g.move(2) ; 112 lines

Output the grid g.display() ; 6 linesChange direction g.face(north) ; 15 lines

Page 29: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-29 Active LearningActive Learning

How many lines of code are represented by the messages How many lines of code are represented by the messages in this program? Show output?in this program? Show output?

#include "grid" #include "grid" // for class grid// for class grid int main()int main() {{ grid tarpit (5, 5, 1, 1, south);grid tarpit (5, 5, 1, 1, south); tarpit.move(3);tarpit.move(3); tarpit.turnLeft();tarpit.turnLeft(); tarpit.move(3);tarpit.move(3); tarpit.turnLeft();tarpit.turnLeft(); tarpit.move(3);tarpit.move(3); tarpit.turnLeft();tarpit.turnLeft(); tarpit.move(3);tarpit.move(3); return 0;return 0; }}

Page 30: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-30 Reasons for functionsReasons for functions

To reuse existing code rather than write it from To reuse existing code rather than write it from scratchscratch

To concentrate on the bigger issues at handTo concentrate on the bigger issues at hand To reduce errors by writing the function only once To reduce errors by writing the function only once

and testing it thoroughlyand testing it thoroughly Programs that once had 1,000 statements in main might now Programs that once had 1,000 statements in main might now

have 100 functions that are 10 lines longhave 100 functions that are 10 lines long With object-orientation, it could be 10 classes with 10 With object-orientation, it could be 10 classes with 10

member functions, that have 10 statements eachmember functions, that have 10 statements each

Page 31: 4-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

4-31Structured and Object-Structured and Object-Oriented ProgrammingOriented Programming

Structured ProgrammingStructured Programming Partition programs into functionsPartition programs into functions The data is passed around from one non-member The data is passed around from one non-member

function to anotherfunction to another Worse yet, the data is made available everywhere Worse yet, the data is made available everywhere

throughout a large program throughout a large program

Object-Oriented ProgrammingObject-Oriented Programming Safely encapsulates collections of functions with the Safely encapsulates collections of functions with the

data they manipulatedata they manipulate