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

43
6-1 Computing Fundamentals with Computing Fundamentals with C++ C++ Object-Oriented Programming and Design, 2nd Object-Oriented Programming and Design, 2nd Edition Edition Rick Mercer Rick Mercer Franklin, Beedle & Associates, 1999 Franklin, Beedle & Associates, 1999 Presentation Copyright 1999, Franklin, Beedle & Presentation Copyright 1999, Franklin, Beedle & Associates Associates Students who buy and instructors who adopt Students who buy and instructors who adopt Computing Fundamentals with C++, Object-Oriented Programming Computing Fundamentals with C++, Object-Oriented Programming and Design 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 presentation as long as this copyright notice remains intact. remains intact.

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

Page 1: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-1

Computing Fundamentals with C++Computing Fundamentals with C++Object-Oriented Programming and Design, 2nd EditionObject-Oriented Programming and Design, 2nd EditionRick MercerRick Mercer

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

Presentation Copyright 1999, Franklin, Beedle & Associates Presentation Copyright 1999, Franklin, Beedle & Associates

Students who buy and instructors who adopt Students who buy 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 are welcome to use this presentation as long as by Rick Mercer are welcome to use this presentation as long as

this copyright notice remains intact.this copyright notice remains intact.

Page 2: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-2Chapter 6: Class Definitions Chapter 6: Class Definitions and Member Functionsand Member Functions

Chapter GoalsChapter Goals Read and understand class definitions (interface Read and understand class definitions (interface

and state).and state).– Exercises and Programming Projects to reinforce reading Exercises and Programming Projects to reinforce reading

and understanding new class interfacesand understanding new class interfaces

Implement class member functions using Implement class member functions using existing class definitions.existing class definitions.

Apply some object-oriented design heuristics.Apply some object-oriented design heuristics.– Exercises and Programming Projects to reinforce member Exercises and Programming Projects to reinforce member

function implementationfunction implementation

Page 3: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-3 6.1 The Interface6.1 The Interface

Abstraction:Abstraction: Act of using and/or understanding something Act of using and/or understanding something

without full knowledge of the implementationwithout full knowledge of the implementation Allows programmer to concentrate on essentialsAllows programmer to concentrate on essentials

how does a grid object move? Not to worry.how does a grid object move? Not to worry. how does string::substr work? Don't need to know.how does string::substr work? Don't need to know.

Abstract level: the interfaceAbstract level: the interface Implementation level: the algorithms and local Implementation level: the algorithms and local

objects in the member functionsobjects in the member functions

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

6-4 6.1.1 Design Decisions with class 6.1.1 Design Decisions with class bankAccountbankAccount

bankAccount could have had bankAccount could have had more operationsmore operations more statemore state

It was kept simple because it is an introductory It was kept simple because it is an introductory example.example.

An account number wasn't present because An account number wasn't present because it's easier to remember "Smith" than "217051931"it's easier to remember "Smith" than "217051931"

Page 5: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-5 What is "good" design?What is "good" design?

Design decisions may be based on makingDesign decisions may be based on making a software component more maintainablea software component more maintainable software that is easy to usesoftware that is easy to use software that can be reused in other applicationssoftware that can be reused in other applications

There are usually tradeoffs to considerThere are usually tradeoffs to consider software may get to market more quickly than the software may get to market more quickly than the

competitors competitors even if it has known errors --- this is a traditioneven if it has known errors --- this is a tradition

There is rarely a perfect designThere is rarely a perfect design Design is influenced by many thingsDesign is influenced by many things

Page 6: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-6 Interface == class definitionInterface == class definition

In a real-world bankAccount, there could be In a real-world bankAccount, there could be many more operations:many more operations:

applyInterest, printMonthlyStatement, applyInterest, printMonthlyStatement, averageDailyBalanceaverageDailyBalance

choosing what operations belong to a class requires choosing what operations belong to a class requires many design decisionsmany design decisions

The design is captured by the class The design is captured by the class interface:interface: the collection of available messages that is the collection of available messages that is

captured in the C++ captured in the C++ class definitionclass definition see next slidesee next slide

Page 7: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-7 6.2 Class Definitions6.2 Class Definitions

classclass class-name class-name { {public:public: class-name() class-name() ;; // Default constructor// Default constructor

class-name(parameter-list) class-name(parameter-list) ; ; // Constructor with parameters// Constructor with parameters

function-heading function-heading ; ; // Member functions that modify state// Member functions that modify state

function-heading function-heading ;; function-heading function-heading constconst ; ; // Members that do not modify state// Members that do not modify state

function-heading function-heading const const ; ; private:private: object-declaration object-declaration // Data members -- the state// Data members -- the state

object-declarationobject-declaration

} } ; ;

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

6-8

class bankAccount {class bankAccount {public:public: bankAccount();bankAccount(); // post: construct a default bankAccount object// post: construct a default bankAccount object bankAccount(string initName, double initBalance);bankAccount(string initName, double initBalance); // post: Initialize bankAccount object with 2 arguments// post: Initialize bankAccount object with 2 arguments void deposit(double depositAmount);void deposit(double depositAmount); // pre: depositAmount > 0.00// pre: depositAmount > 0.00 // post: credit depositAmount to this object's balance // post: credit depositAmount to this object's balance void withdraw(double withdrawalAmount);void withdraw(double withdrawalAmount); // pre: 0 <= withdrawalAmount <= balance// pre: 0 <= withdrawalAmount <= balance // post:debit withdrawalAmount from object's balance// post:debit withdrawalAmount from object's balance double balance() const;double balance() const; // post: return this object's current account balance// post: return this object's current account balance string name() const;string name() const; // post: return this object's identification name// post: return this object's identification nameprivate:private: string my_name; string my_name; // The unique account identification// The unique account identification double my_balance; double my_balance; // Stores the current balance// Stores the current balance};};

Class definitions: An exampleClass definitions: An examplewith commentswith comments

Page 9: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-9 Class Definitions Class Definitions continuedcontinued

The class definition The class definition shows what messages are available shows what messages are available provides information necessary for sending messages provides information necessary for sending messages

it has a collection of member function headingsit has a collection of member function headings

member function name, return type, number of parametersmember function name, return type, number of parameters represents the interface, which is the collection of represents the interface, which is the collection of

available messagesavailable messages

Page 10: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-10 Class Definitions Class Definitions continuedcontinued

The following things can be determined from a The following things can be determined from a class definitionclass definition

The class nameThe class name The name of all member functionsThe name of all member functions The return type of any non-void functionThe return type of any non-void function The number and class of arguments required in any The number and class of arguments required in any

member function callmember function call The action of each member function through The action of each member function through

postconditions postconditions if it has comments, that isif it has comments, that is

Page 11: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-11Objects are a lot about Objects are a lot about Operations and StateOperations and State

The The function-headings function-headings after public: represent the after public: represent the messages that may be sent to any objectmessages that may be sent to any object

The The data-membersdata-members after after private:private: are what stores are what stores the state of any objectthe state of any object

every instance of a class has it own separate stateevery instance of a class has it own separate state

Page 12: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-12The same class without pre and The same class without pre and post conditions post conditions code orientedcode oriented

class bankAccount {class bankAccount {public: public: // OPERATIONS// OPERATIONS//--constructors//--constructors bankAccount();bankAccount(); bankAccount(string initName, double initBalance);bankAccount(string initName, double initBalance);//--modifiers//--modifiers void deposit(double depositAmount);void deposit(double depositAmount); void withdraw(double withdrawalAmount);void withdraw(double withdrawalAmount);//--accessors//--accessors double balance() const;double balance() const; string name() const;string name() const;private: private: // STATE// STATE string my_name; string my_name; double my_balance; double my_balance; };};

Page 13: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-13 class diagram class diagram summary of operations and statesummary of operations and state

void withdraw(double) void deposit(double) double balance() string name()

string my_name double my_balance

bankAccount

Page 14: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-14 Sample MessagesSample Messages

#include <iostream>#include <iostream>using namespace std;using namespace std;#include "baccount" #include "baccount" // for class bankAccount// for class bankAccountint main()int main(){ { // Test drive bankAccount// Test drive bankAccount bankAccount defaultAccount; bankAccount defaultAccount; // Initialize// Initialize bankAccount anAcct("Bob", 50.00); bankAccount anAcct("Bob", 50.00); // Initialize // Initialize

anAcct.withdraw(20.00); anAcct.withdraw(20.00); // Modify// Modify anAcct.deposit(40.00); anAcct.deposit(40.00); // Modify// Modify cout << anAcct.name() << endl; cout << anAcct.name() << endl; // Access// Access cout << anAcct.balance() << endl; cout << anAcct.balance() << endl; // Access// Access return 0;return 0;}}

Page 15: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-15 6.6.2 Constructors6.6.2 Constructors

The first two function headings for The first two function headings for bankAccountbankAccount differs from the other members differs from the other members

they have no return typethey have no return type they have the same name as the classthey have the same name as the class

These are the constructor functionsThese are the constructor functions create three default bankAccount objects:create three default bankAccount objects:

bankAccount a, b, c;bankAccount a, b, c;

initialize one initialized instance of the class:initialize one initialized instance of the class: bankAccount anAcct("Bob", 123.45);bankAccount anAcct("Bob", 123.45);

Page 16: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-16 Constructors Constructors continuedcontinued

Other constructor messages:Other constructor messages: string s1, s2, s3;string s1, s2, s3; string name("First I. L. Last");string name("First I. L. Last");

bankAccount a1, a2, a3;bankAccount a1, a2, a3;

bankAccount anotherAcct("CH1234", 5678.90);bankAccount anotherAcct("CH1234", 5678.90);

General form for object construction:General form for object construction:

class-name object-name-list class-name object-name-list ;;

-or--or-

class-name object-nameclass-name object-name (( initial-stateinitial-state ) ;) ;

Page 17: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-17 6.3 The State Object Pattern6.3 The State Object Pattern

Many classes have these things in commonMany classes have these things in common private data members store the state of objects private data members store the state of objects constructors initialize private data membersconstructors initialize private data members modifiers alter the private data membersmodifiers alter the private data members accessors allow us to inspect the current state of accessors allow us to inspect the current state of

an object or to have its state available in an object or to have its state available in expressionsexpressions

Page 18: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-18 Object PatternObject Pattern

An object pattern is a guide for designing and An object pattern is a guide for designing and implementing new classes implementing new classes

The state object pattern describes objects that The state object pattern describes objects that Maintain a body of data and provide suitable access Maintain a body of data and provide suitable access

to it by other objects and human usersto it by other objects and human users Object patterns help us understand new objectsObject patterns help us understand new objects The state object pattern summarizes many of The state object pattern summarizes many of

the classes you will implement at first the classes you will implement at first

Page 19: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-19

Pattern: State Object

Problem: Maintain a body of data and provide

suitable access to it by other object

and human users

Outline: classclass a-descriptive-class-name {{public:public: default-constructor // default state// default state constructors(initial-state) modifying-functions accessing-functions private:private: data-members // the state// the state};};

Page 20: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-20 6.3.1 Using Constructors, 6.3.1 Using Constructors, Modifiers, and AccessorsModifiers, and Accessors

Constructors Constructors initialize the state of an object:initialize the state of an object:

string s2("initial string"); string s2("initial string"); // State of s2 is "initial string"// State of s2 is "initial string"

string aDefaultString;string aDefaultString;// State of aDefaultString is ""// State of aDefaultString is ""

bankAccount anAcct("Early Grey", 2150.67);bankAccount anAcct("Early Grey", 2150.67);// Early Grey has a starting balance of 2,150.67// Early Grey has a starting balance of 2,150.67

bankAccount aDefaultAccount;bankAccount aDefaultAccount;// aDefaultAccount.name() would return "?name?"// aDefaultAccount.name() would return "?name?"// and aDefaultAccount.balance() would return 0.0// and aDefaultAccount.balance() would return 0.0

Page 21: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-21 Using ModifiersUsing Modifiers

ModifiersModifiers alter the state of an object: alter the state of an object:

string s2("initial string"); string s2("initial string");

s2.replace(1, 3, "NEW"); s2.replace(1, 3, "NEW");

// s2 is "iNEWial string"// s2 is "iNEWial string"

aGrid.move(5);aGrid.move(5);

// The mover is 5 spaces forward// The mover is 5 spaces forward

anAccount.withdraw(120.00) anAccount.withdraw(120.00)

// Balance is reduced by 120.00// Balance is reduced by 120.00

Page 22: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-22 Using AccessorsUsing Accessors

AccessorsAccessors either return the current value of an either return the current value of an object's data member, or return some object's data member, or return some information related to the state of an object:information related to the state of an object:

s2.length() s2.length() // Return the dynamic length// Return the dynamic length g.row() g.row() // Tell me where the mover is// Tell me where the mover is g.column()g.column() myAccount.balance()myAccount.balance()// Get current balance// Get current balance aBook.borrower() aBook.borrower() // who has the book// who has the book s2.substr(0, 3) s2.substr(0, 3) // A piece of the string// A piece of the string

Page 23: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-23 Naming ConventionsNaming Conventions

Rules #1, 2, and 3:Rules #1, 2, and 3:1: Always use meaningful names1: Always use meaningful names2: Always use meaningful names2: Always use meaningful names3: Always use meaningful names3: Always use meaningful names

Rule #4Rule #4

Constuctors:Constuctors: Name of the className of the classModifiers:Modifiers: Verbs Verbs borrowBook withdrawborrowBook withdraw

Accessors:Accessors: Nouns Nouns length row nRowslength row nRows could use getLength, getRow, getnRowscould use getLength, getRow, getnRows

Page 24: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-24 6.4 public: or private:6.4 public: or private:

When designing a class, do this When designing a class, do this at least for nowat least for now

place operations under place operations under public:public: place object that store state under place object that store state under private:private:

Public messages can be sent from the block in Public messages can be sent from the block in which the object is declaredwhich the object is declared

Private state can not be messed up like thisPrivate state can not be messed up like this bankAccount myAcct("Me", 10.00);bankAccount myAcct("Me", 10.00); myAcct.my_balance = myAcct.my_balance + 999999.99; myAcct.my_balance = myAcct.my_balance + 999999.99; //... //...

Page 25: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-25 Protecting an Object's StateProtecting an Object's State

Access modes make operations available to Access modes make operations available to clients and also protect the stateclients and also protect the state

The scope of members is as follows:The scope of members is as follows:

Access ModeAccess Mode Where is the member known? Where is the member known? scopescope

public:public: In all class member functions and in the In all class member functions and in the block of the client code where the object block of the client code where the object

has been declared has been declared in main for instancein main for instance

private:private: Only to class members functions.Only to class members functions.

Page 26: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-26 Why is the state private?Why is the state private?

Recommendations:Recommendations: consistently declare operations after consistently declare operations after public:public: and data members after and data members after private:private:

A public operation can be used by the clientA public operation can be used by the client private data avoids direct access to state:private data avoids direct access to state: myAccount.my_balance = 1000000.00;myAccount.my_balance = 1000000.00;

Now, to modify the state, we must go through Now, to modify the state, we must go through the proper channels--deposit.the proper channels--deposit.

Page 27: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-27 Another State Object ExampleAnother State Object Example

class student {class student {public:public://--constructors//--constructors student();student(); student(string initName, student(string initName, double initCredits, double initCredits, double initQualityPoints);double initQualityPoints);// --modifier(s)// --modifier(s) void set_name(string newName);void set_name(string newName); void recordCourse(double credits,void recordCourse(double credits, double numericGrade);double numericGrade);// --accessor(s)// --accessor(s) double GPA() const;double GPA() const; string name() const;string name() const;private: private: string my_name; string my_name; // ID// ID double my_credits; double my_credits; // credits completed// credits completed double my_QualityPoints; double my_QualityPoints; // sum of credits*grades// sum of credits*grades};};

Page 28: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-28 Active LearningActive Learning

Class name ______________? Class name ______________? Operations names _______________?Operations names _______________? Names of objects that store state _____________?Names of objects that store state _____________? # arguments for # arguments for recordCourserecordCourse ____________?____________? Return type of Return type of GPAGPA _____________? _____________? # arguments for # arguments for GPAGPA ____________?____________? Write code that initializes one student object records Write code that initializes one student object records

two courses and shows the GPA two courses and shows the GPA elsewhereelsewhere

What value is returned for your student ? ____?What value is returned for your student ? ____?

Page 29: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-29 6.4.1 Separating Interface from 6.4.1 Separating Interface from ImplementationImplementation

Class definitions are usually stored in .h filesClass definitions are usually stored in .h files The implementations of those member The implementations of those member

functions are usually stored in .cpp filesfunctions are usually stored in .cpp files Separating interface from implementation is a Separating interface from implementation is a

sound software engineering principlesound software engineering principle But to construct objects when the class is in But to construct objects when the class is in

two separate files requires some extra worktwo separate files requires some extra work or the little "trick" on the next slide or the little "trick" on the next slide

Page 30: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-30 Keeping things simpleKeeping things simple but not traditional to save compile timebut not traditional to save compile time

Most author-supplied classes have 3 filesMost author-supplied classes have 3 files The file name with no dot '.' #includes both the The file name with no dot '.' #includes both the

class definition and the member function class definition and the member function implementations automatically:implementations automatically:

// File name: baccount#ifndef _BACCOUNT_ // These safeguards prevent#define _BACCOUNT_ // duplicate compilation #include "baccount.h" // class bankAccount definition#include "baccount.cpp" // function implementation#endif

Page 31: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-316.5 Implementing Class 6.5 Implementing Class Member FunctionsMember Functions

Class member function implementation are Class member function implementation are similar to their non-member counterparts similar to their non-member counterparts

All class member functions must be qualified All class member functions must be qualified with the class name and :: resolution operatorwith the class name and :: resolution operator

void bankAccount::withdraw(double amount)void bankAccount::withdraw(double amount) {{ // This function can reference private data!// This function can reference private data! }}

constructors cannot have a return typeconstructors cannot have a return type bankAccount::bankAccount(string initName,bankAccount::bankAccount(string initName, double initBalance)double initBalance)

Page 32: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-32 6.5.1 Implementing Constructors6.5.1 Implementing Constructors

The following default constructor The following default constructor (no arguments)(no arguments) bankAccount::bankAccount()bankAccount::bankAccount() {{ my_name = "?name?";my_name = "?name?"; my_balance = 0.0;my_balance = 0.0; }}

is called three times with this code:is called three times with this code: bankAccount a1, a2, a3;bankAccount a1, a2, a3;

Each has the same default state. Each has the same default state. output: ?__________?output: ?__________?

cout << a1.name() << a2.name() << a3.name();cout << a1.name() << a2.name() << a3.name(); cout << a1.balance() << a2.balance() cout << a1.balance() << a2.balance() << a3.balance();<< a3.balance();

Page 33: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-33 Constructors with parametersConstructors with parameters

The following constructor with parametersThe following constructor with parameters bankAccount::bankAccount(string initName, bankAccount::bankAccount(string initName, double initBalance)double initBalance) { { my_name = initName;my_name = initName; my_balance = initBalance;my_balance = initBalance; }}

is called whenever bankAccount objects are is called whenever bankAccount objects are constructed with arguments like this:constructed with arguments like this:

bankAccount initialized("Glass", 2500.00);bankAccount initialized("Glass", 2500.00); bankAccount another("Dunham", 100.00);bankAccount another("Dunham", 100.00);

Page 34: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-34 6.5.2 Implementing Modifiers6.5.2 Implementing Modifiers

Modifying functions are implemented like non Modifying functions are implemented like non members except they must be qualified with members except they must be qualified with class-nameclass-name :: ::

This gives the modifier access to the state that is to be This gives the modifier access to the state that is to be modified.modified.

In this example, the private data member In this example, the private data member my_balancemy_balance is changed: is changed: so do not use constso do not use const

void bankAccount::deposit(double depositAmount)void bankAccount::deposit(double depositAmount) { { // post: my_balance has depositAmount added// post: my_balance has depositAmount added my_balance = my_balance + depositAmount;my_balance = my_balance + depositAmount; }}

Page 35: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-35 6.5.3 Implementing Accessors:6.5.3 Implementing Accessors:

Accessor functions must also be qualified with Accessor functions must also be qualified with class-nameclass-name :: to gives access to the state to being :: to gives access to the state to being used to return info. used to return info. remember to write remember to write constconst

double bankAccount::balance() constdouble bankAccount::balance() const { { // no processing is necessary. Just return it.// no processing is necessary. Just return it. return my_balance;return my_balance; }}

In this example, the private data member In this example, the private data member my_balancemy_balance is made available like this: is made available like this:

cout << anAcct.balance() << endl;cout << anAcct.balance() << endl;

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

6-366.6 Object-Oriented Design 6.6 Object-Oriented Design HeuristicsHeuristics

Classes must be designedClasses must be designed There are some heuristics (guidelines) to help us There are some heuristics (guidelines) to help us

make design decisionsmake design decisions

Design Heuristic 6-1Design Heuristic 6-1

All data should be hidden within its classAll data should be hidden within its class

Ramifications: Ramifications: Good: Can't mess up the state (compiler complains) Good: Can't mess up the state (compiler complains) Good: Have to create interface of member functionsGood: Have to create interface of member functions Bad: Extra coding, but worth it Bad: Extra coding, but worth it

Page 37: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-37 6.6.1 Cohesion Within a Class6.6.1 Cohesion Within a Class

A class definition provides the public interface--A class definition provides the public interface--messages should be closely relatedmessages should be closely related

The related data objects necessary to carry out a The related data objects necessary to carry out a message should be in the classmessage should be in the class

Design Heuristic 6-2Design Heuristic 6-2

Keep related data and behavior in one placeKeep related data and behavior in one place RamificationsRamifications

Good: Provides intuitive collection of operations Good: Provides intuitive collection of operations Good: Reduces the number of arguments in messagesGood: Reduces the number of arguments in messages Bad: None that I can think ofBad: None that I can think of

Page 38: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-38 Cohesion Cohesion continuedcontinued

For example, cohesion means For example, cohesion means the bankAccount class does not have operations the bankAccount class does not have operations

like like dealCardDeckdealCardDeck or or ambientTemperatureambientTemperature the bankAccount class has access to the balance, the bankAccount class has access to the balance,

something which often needs to be referenced. something which often needs to be referenced. The balance (named The balance (named my_balancemy_balance) is not maintained ) is not maintained

separately or passed as an argumentseparately or passed as an argument

Page 39: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-39 Cohesion Cohesion continuedcontinued

Synonyms for cohesion:Synonyms for cohesion: hanging togetherhanging together unity, adherence, solidarityunity, adherence, solidarity

Cohesion meansCohesion means data objects are related to the operationsdata objects are related to the operations operations are related to the data objectsoperations are related to the data objects data and operations are part of the same class data and operations are part of the same class

definitiondefinition

Page 40: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-40 6.6.2 Why are Accessors const and 6.6.2 Why are Accessors const and Modifiers not?Modifiers not?

Have you noticed that const follows all Have you noticed that const follows all accessing functions? accessing functions? but not any othersbut not any others

It necessary to make our new classes behave It necessary to make our new classes behave like the standard classeslike the standard classes

specifically, it is necessary to allow objects passed specifically, it is necessary to allow objects passed by const reference to behave correctlyby const reference to behave correctly

such parameters should allow the accessing such parameters should allow the accessing messages to be sent, but not any modifing messagemessages to be sent, but not any modifing message

Page 41: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-41 const messages okay, all others are notconst messages okay, all others are not

void display(const bankAccount & b)void display(const bankAccount & b){{ // OKAY to send name and balance messages since they// OKAY to send name and balance messages since they // were both declared with const member functions// were both declared with const member functions cout << "{ bankAccount: " << b.name() cout << "{ bankAccount: " << b.name() << ", $" << b.balance() << " }" << endl;<< ", $" << b.balance() << " }" << endl;

// Modifying message to non-const member function// Modifying message to non-const member function // was not tagged as const. It should be an ERROR// was not tagged as const. It should be an ERROR b.withdraw(234.56);b.withdraw(234.56);}}

Note: Turbo/Borland C++ reduces the error to a warning. Note: Turbo/Borland C++ reduces the error to a warning. This is not good. This is not good.

Page 42: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-42 A C++ specific heuristicA C++ specific heuristic

This leads to another guideline that is particular This leads to another guideline that is particular to C++ to C++

Design Heuristic 6-3Design Heuristic 6-3

Always declare accessor member functions asAlways declare accessor member functions as const. Never declare modifiers as constconst. Never declare modifiers as const This guideline is easy to forgetThis guideline is easy to forget

Unless you thoroughly test, you may not get a Unless you thoroughly test, you may not get a compiletime error. compiletime error. You will not be told something is wrong until you try to You will not be told something is wrong until you try to

pass an instance of your new class by const reference. pass an instance of your new class by const reference.

Page 43: 6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.

6-43Forgetting const == Forgetting const == compiletime error messagecompiletime error message

The programming projects ask you to implement The programming projects ask you to implement member functionsmember functions

the class definition is giventhe class definition is given If the class definition has If the class definition has constconst, you must write, you must write constconst in the member function implementation alsoin the member function implementation also

ERROR: overloaded member function not found in 'X'ERROR: overloaded member function not found in 'X'

// file X.h// file X.hclass X {class X { int foo() const;int foo() const; … …};};

// file X.cpp headings must match!// file X.cpp headings must match!int foo()int foo(){{ … …}}