Classes: A Deeper Look, Part 2

Similar documents
1 // Fig. 6.13: time2.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> Outline. 4 5 using std::cout; 6 7 #include <iomanip>

Computer Programming with C++ (21)

Classes: A Deeper Look. Systems Programming

A Deeper Look at Classes

Fig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10

W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls

Computer Programming Class Members 9 th Lecture

Angela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan.

Pointer Assignments. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 18 October 29, The new Operator

Chapter 17 - C++ Classes: Part II

Preview 11/1/2017. Constant Objects and Member Functions. Constant Objects and Member Functions. Constant Objects and Member Functions

OBJECT ORIENTED PROGRAMMING USING C++

Classes: A Deeper Look, Part 1

Chapter 6: Classes and Data Abstraction

Classes: A Deeper Look

9.1 Introduction. Integrated Time class case study Preprocessor wrapper Three types of handles on an object. Class functions

57:017, Computers in Engineering C++ Classes

More C++ Classes. Systems Programming

IS 0020 Program Design and Software Tools

Introduction to Programming session 24

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools

Chapter 16: Classes and Data Abstraction

Classes and Objects: A Deeper Look

Chapter 9 Classes : A Deeper Look, Part 1

Fundamentals of Programming Session 24

Classes and Data Abstraction. Topic 5

Operator Overloading

Classes and Objects: A Deeper Look

W8.2 Operator Overloading

Introduction. W8.2 Operator Overloading

Deitel Dive-Into Series: Dive-Into Cygwin and GNU C++

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

CS 1337 Computer Science II Page 1

Chapter 7: Classes Part II

Operator Overloading

Classes and Objects: A Deeper Look

Preview 9/20/2017. Object Oriented Programing with C++ Object Oriented Programing with C++ Object Oriented Programing with C++

Homework 3. Due: Feb 25, 23:59pm. Section 1 (20 pts, 2 pts each) Multiple Choice Questions

Operator Overloading

Inheritance and Polymorphism

Operator Overloading in C++ Systems Programming

clarity. In the first form, the access specifier public : is needed to {

Fundamentals of Programming Session 25

Encapsulation. Contents. Steven Zeil. July 17, Encapsulation Encapsulation in C Classes 4. 3 Hiding Attributes 8

Classes and Data Abstraction

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

Chapter 18 - C++ Operator Overloading

CIS 190: C/C++ Programming. Classes in C++

l A class in C++ is similar to a structure. l A class contains members: - variables AND - public: accessible outside the class.

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

An inline function is one in which the function code replaces the function call directly. Inline class member functions

Do not turn to the next page until the start of the exam.

Classes and Data Abstraction. Topic 5

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Operator Overloading

The Class. Classes and Objects. Example class: Time class declaration with functions defined inline. Using Time class in a driver.

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

1 OBJECT-BASED PROGRAMMING CHAPTER 8

Arrays. Week 4. Assylbek Jumagaliyev

Chapter 15 - C++ As A "Better C"

Software Design Abstract Data Types

Assignment 2 Solution

Object Oriented Design

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

this Pointer, Constant Functions, Static Data Members, and Static Member Functions this Pointer (11.1) Example of this pointer

Due Date: See Blackboard

CSCI-1200 Data Structures Fall 2018 Lecture 3 Classes I

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Classes and Objects. Types and Classes. Example. Object Oriented Programming

Practice Problems CS2620 Advanced Programming, Spring 2003

Due Date: See Blackboard

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Fast Introduction to Object Oriented Programming and C++

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

Classes and Objects:A Deeper Look

CS242 COMPUTER PROGRAMMING

Introduction to C++ Systems Programming

Lecture 5. Function Pointers

Object-Based Programming

Intermediate Programming, Spring 2017*

IS 0020 Program Design and Software Tools

Programming Assignment #2

Operator overloading: extra examples

6.096 Introduction to C++

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1

CS201 Latest Solved MCQs

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011

Ich habe in allen Klassen konsequent ClassInvariant umgesetzt, als Beispiel dient hier eine der komplexeren Versionen, nämlich die in CHouse:

Unit Testing. Contents. Steven Zeil. July 22, Types of Testing 2. 2 Unit Testing Scaffolding Drivers Stubs...

CSCE 110 PROGRAMMING FUNDAMENTALS

Unit Testing. Steven Zeil. July 22, Types of Testing 2. 2 Unit Testing Scaffolding Drivers Stubs...

Transcription:

10 But what, to serve our private ends, Forbids the cheating of our friends? Charles Churchill Instead of this absurd division into sexes they ought to class people as static and dynamic. Evelyn Waugh Have no friends not equal to yourself. Confucius Classes: A Deeper Look, Part 2 OBJECTIVES In this chapter you will learn: To specify const (constant) objects and const member functions. To create objects composed of other objects. To use friend functions and friend classes. To use the this pointer. To create and destroy objects dynamically with operators new and delete, respectively. To use static data members and member functions. The concept of a container class. The notion of iterator classes that walk through the elements of container classes. To use proxy classes to hide implementation details from a class s clients.

524 Chapter 10 Classes: A Deeper Look, Part 2 Self-Review Exercises 10.1 Fill in the blanks in each of the following: a) must be used to initialize constant members of a class. ANS: member initializers. b) A nonmember function must be declared as a(n) of a class to have access to that class s private data members. ANS: friend. c) The operator dynamically allocates memory for an object of a specified type and returns a to that type. ANS: new, pointer. d) A constant object must be ; it cannot be modified after it is created. ANS: initialized. e) A(n) data member represents class-wide information. ANS: static. f) An object s non-static member functions have access to a self pointer to the object called the pointer. ANS: this. g) The keyword specifies that an object or variable is not modifiable after it is initialized. ANS: const. h) If a member initializer is not provided for a member object of a class, the object's is called. ANS: default constructor. i) A member function should be declared static if it does not access class members. ANS: non-static. j) Member objects are constructed their enclosing class object. ANS: before. k) The operator reclaims memory previously allocated by new. ANS: delete. 10.2 Find the errors in the following class and explain how to correct them: class Example { public: Example( int y = 10 ) : data( y ) { // empty body } // end Example constructor int getincrementeddata() const { return data++; } // end function getincrementeddata static int getcount() { cout << "Data is " << data << endl; return count; } // end function getcount private: int data;

Exercises 525 Exercises static int count; }; // end class Example ANS: Error: The class definition for Example has two errors. The first occurs in function getincrementeddata. The function is declared const, but it modifies the object. Correction: To correct the first error, remove the const keyword from the definition of getincrementeddata. Error: The second error occurs in function getcount. This function is declared static, so it is not allowed to access any non-static member of the class. Correction: To correct the second error, remove the output line from the getcount definition. 10.3 Compare and contrast dynamic memory allocation and deallocation operators new, new [], delete and delete []. ANS: Operator new creates an object and dynamically allocates space in memory for that object. Operator delete destroys a dynamically allocated object and frees the space that was occupied by the object. Operators new [] and delete [] are used to allocate and deallocate arrays dynamically. 10.4 Explain the notion of friendship in C++. Explain the negative aspects of friendship as described in the text. ANS: Functions that are declared as friends of a class have access to that class s private and protected members. Some people in the object-oriented programming community prefer not to use friend functions. Such people believe friendship corrupts information hiding and weakens the value of the object-oriented design approach, because friend functions can directly access a class s implementation details that are supposed to be hidden. 10.5 Can a correct Time class definition include both of the following constructors? If not, explain why not. Time( int h = 0, int m = 0, int s = 0 ); Time(); ANS: No. There is ambiguity between the two constructors. When a call is made to the default constructor, the compiler cannot determine which one to use because both constructors can be called with no arguments. 10.6 What happens when a return type, even void, is specified for a constructor or destructor? ANS: A compilation error occurs. A programmer cannot specify a return type for a constructor or destructor. 10.7 Modify class Date in Fig. 10.10 to have the following capabilities: a) Output the date in multiple formats such as DDD YYYY MM/DD/YY June 14, 1992 b) Use overloaded constructors to create Date objects initialized with dates of the formats in part (a).

526 Chapter 10 Classes: A Deeper Look, Part 2 c) Create a Date constructor that reads the system date using the standard library functions of the <ctime> header and sets the Date members. (See your compiler s reference documentation or www.cplusplus.com/ref/ctime/index.html for information on the functions in header <ctime>.) In Chapter 11, we will be able to create operators for testing the equality of two dates and for comparing dates to determine whether one date is prior to, or after, another. ANS: 1 // Exercise 10.7 Solution: Date.h 2 // Date class definition; Member functions defined in Date.cpp 3 #ifndef DATE_H 4 #define DATE_H 5 6 #include <string> 7 using std::string; 8 9 class Date 10 { 11 public: 12 Date(); // default constructor uses <ctime> functions to set date 13 Date( int, int ); // constructor using ddd yyyy format 14 Date( int, int, int ); // constructor using dd/mm/yy format 15 Date( string, int, int ); // constructor using Month dd, yyyy format 16 void setday( int ); // set the day 17 void setmonth( int ); // set the month 18 void print() const; // print date in month/day/year format 19 void printdddyyyy() const; // print date in ddd yyyy format 20 void printmmddyy() const; // print date in mm/dd/yy format 21 void printmonthddyyyy() const; // print date in Month dd, yyyy format 22 ~Date(); // provided to confirm destruction order 23 private: 24 int month; // 1-12 (January-December) 25 int day; // 1-31 based on month 26 int year; // any year 27 28 // utility functions 29 int checkday( int ) const; // check if day is proper for month and year 30 int daysinmonth( int ) const; // returns number of days in given month 31 bool isleapyear() const; // indicates whether date is in a leap year 32 int convertddtoddd() const; // get 3-digit day based on month and day 33 void setmmddfromddd( int ); // set month and day based on 3-digit day 34 string convertmmtomonth( int ) const; // convert mm to month name 35 void setmmfrommonth( string ); // convert month name to mm 36 int convertyyyytoyy() const; // get 2-digit year based on 4-digit year 37 void setyyyyfromyy( int ); // set year based on 2-digit year 38 }; // end class Date 39 40 #endif 1 // Exercise 10.7 Solution: Date.cpp 2 // Member-function definitions for class Date. 3 #include <iostream>

Exercises 527 4 using std::cout; 5 using std::endl; 6 7 #include <iomanip> 8 using std::setw; 9 using std::setfill; 10 11 #include <ctime> 12 using std::time; 13 using std::localtime; 14 using std::tm; 15 using std::time_t; 16 17 #include "Date.h" // include Date class definition 18 19 // default constructor that sets date using <ctime> functions 20 Date::Date() 21 { 22 // pointer of type struct tm which holds calendar time components 23 struct tm *ptr; 24 25 time_t t = time( 0 ); // determine current calendar time 26 27 // convert current calendar time pointed to by t into 28 // broken down time and assign it to ptr 29 ptr = localtime( &t ); 30 31 day = ptr->tm_mday; // broken down day of month 32 month = 1 + ptr->tm_mon; // broken down month since January 33 year = ptr->tm_year + 1900; // broken down year since 1900 34 } // end Date constructor 35 36 // constructor that takes date in ddd yyyy format 37 Date::Date( int ddd, int yyyy ) 38 { 39 year = yyyy; // could validate 40 setmmddfromddd( ddd ); // set month and day based on ddd 41 } // end Date constructor 42 43 // constructor that takes date in mm/dd/yy format 44 Date::Date( int mm, int dd, int yy ) 45 { 46 setyyyyfromyy( yy ); // set 4-digit year based on yy 47 setmonth( mm ); // validate and set the month 48 setday( dd ); // validate and set the day 49 } // end Date constructor 50 51 // constructor that takes date in Month dd, yyyy format 52 Date::Date( string monthname, int dd, int yyyy ) 53 { 54 setmmfrommonth( monthname ); // set month based on month name 55 setday( dd ); // validate and set the day 56 year = yyyy; // could validate 57 } // end Date constructor 58

528 Chapter 10 Classes: A Deeper Look, Part 2 59 // validate and store the day 60 void Date::setDay( int d ) 61 { 62 day = checkday( d ); // validate the day 63 } // end function setday 64 65 // validate and store the month 66 void Date::setMonth( int m ) 67 { 68 if ( m > 0 && m <= 12 ) // validate the month 69 month = m; 70 else 71 { 72 month = 1; // invalid month set to 1 73 cout << "Invalid month (" << m << ") set to 1.\n"; 74 } // end else 75 } // end function setmonth 76 77 // print Date object in form: month/day/year 78 void Date::print() const 79 { 80 cout << month << '/' << day << '/' << year << endl; 81 } // end function print 82 83 // print Date object in form: ddd yyyy 84 void Date::printDDDYYYY() const 85 { 86 cout << convertddtoddd() << ' ' << year << endl; 87 } // end function printdddyyyy 88 89 // print Date object in form: mm/dd/yy 90 void Date::printMMDDYY() const 91 { 92 cout << setw( 2 ) << setfill( '0' ) << month << '/' 93 << setw( 2 ) << setfill( '0' ) << day << '/' 94 << setw( 2 ) << setfill( '0' ) << convertyyyytoyy() << endl; 95 } // end function printmmddyy 96 97 // print Date object in form: Month dd, yyyy 98 void Date::printMonthDDYYYY() const 99 { 100 cout << convertmmtomonth( month ) << ' ' << day << ", " << year 101 << endl; 102 } // end function printmonthddyyyy 103 104 // output Date object to show when its destructor is called 105 Date::~Date() 106 { 107 cout << "Date object destructor for date "; 108 print(); 109 cout << endl; 110 } // end ~Date destructor 111 112 // utility function to confirm proper day value based on 113 // month and year; handles leap years, too

Exercises 529 114 int Date::checkDay( int testday ) const 115 { 116 // determine whether testday is valid for specified month 117 if ( testday > 0 && testday <= daysinmonth( month ) ) 118 return testday; 119 120 // February 29 check for leap year 121 if ( month == 2 && testday == 29 && isleapyear() ) 122 return testday; 123 124 cout << "Invalid day (" << testday << ") set to 1.\n"; 125 return 1; // leave object in consistent state if bad value 126 } // end function checkday 127 128 // return the number of days in a month 129 int Date::daysInMonth( int m ) const 130 { 131 if ( isleapyear() && m == 2 ) 132 return 29; 133 134 static const int dayspermonth[ 13 ] = 135 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 136 137 return dayspermonth[ m ]; 138 } // end function daysinmonth 139 140 // test for a leap year 141 bool Date::isLeapYear() const 142 { 143 if ( year % 400 == 0 ( year % 4 == 0 && year % 100!= 0 ) ) 144 return true; 145 else 146 return false; 147 } // end function isleapyear 148 149 // calculate 3-digit day based on Date object's current month and day 150 int Date::convertDDToDDD() const 151 { 152 int ddd = 0; 153 154 // for each month that has passed, add days to ddd 155 for ( int i = 1; i < month; i++ ) 156 ddd += daysinmonth( i ); 157 158 // add days from current month 159 ddd += day; 160 161 return ddd; 162 } // end function convertddtoddd 163 164 // set month and day based on 3-digit day 165 void Date::setMMDDFromDDD( int ddd ) 166 { 167 int daytotal = 0; 168 int m;

530 Chapter 10 Classes: A Deeper Look, Part 2 169 170 for ( m = 1; m <= 12 && ( daytotal + daysinmonth( m ) ) < ddd; m++ ) 171 daytotal += daysinmonth( m ); 172 173 setmonth( m ); 174 setday( ddd - daytotal ); 175 } // end function setmmddfromddd 176 177 // utility function to convert month number to month name 178 string Date::convertMMToMonth( int mm ) const 179 { 180 static const string months[] = 181 { "", "January", "February", "March", "April", "May", "June", 182 "July", "August", "September", "October", "November", "December" }; 183 184 return months[ mm ]; 185 } // end function convertmmtomonth 186 187 // set month number based on month name 188 void Date::setMMFromMonth( string m ) 189 { 190 bool matchfound = false; 191 192 // loop for each month, checking for a match 193 for ( int i = 1; i <= 12 &&!matchfound; i++ ) 194 { 195 string tempmonth = convertmmtomonth( i ); 196 197 if ( tempmonth == m ) 198 { 199 setmonth( i ); 200 matchfound = true; 201 } // end if 202 } // end for 203 204 if (!matchfound ) 205 { 206 cout << "Invalid month name (" << month << "). month set to 1.\n"; 207 setmonth( 1 ); // leave object in consistent state if bad value 208 } // end if 209 } // end function setmmfrommonth 210 211 // utility function to convert 4-digit year to 2-digit year 212 int Date::convertYYYYToYY() const 213 { 214 // if year is in 2000s, subtract 2000 215 // else, assume year is in the 1900s and subtract 1900 216 return ( year >= 2000? year - 2000 : year - 1900 ); 217 } // end function convertyyyytoyy 218 219 // utility function to convert 2-digit year to 4-digit year 220 void Date::setYYYYFromYY( int yy ) 221 { 222 // if yy is less than 7, assume its in the 2000s 223 // if yy is greater than or equal to 7, assume it's in the 1900s

Exercises 531 224 year = ( yy < 7? yy + 2000 : yy + 1900 ); 225 } // end function setyyyyfromyy 1 // Exercise 10.7 Solution: ex10_07.cpp 2 // Driver program for class Date. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 7 #include "Date.h" // include Date class definition 8 9 int main() 10 { 11 Date date1( 256, 1999 ); // initialize using ddd yyyy format 12 Date date2( 3, 25, 04 ); // initialize using mm/dd/yy format 13 Date date3( "September", 1, 2000 ); // "month" dd, yyyy format 14 Date date4; // initialize to current date with default constructor 15 16 // print Date objects in default format 17 date1.print(); 18 date2.print(); 19 date3.print(); 20 date4.print(); 21 cout << '\n'; 22 23 // print Date objects in 'ddd yyyy' format 24 date1.printdddyyyy(); 25 date2.printdddyyyy(); 26 date3.printdddyyyy(); 27 date4.printdddyyyy(); 28 cout << '\n'; 29 30 // print Date objects in 'mm/dd/yy' format 31 date1.printmmddyy(); 32 date2.printmmddyy(); 33 date3.printmmddyy(); 34 date4.printmmddyy(); 35 cout << '\n'; 36 37 // print Date objects in '"month" d, yyyy' format 38 date1.printmonthddyyyy(); 39 date2.printmonthddyyyy(); 40 date3.printmonthddyyyy(); 41 date4.printmonthddyyyy(); 42 cout << endl; 43 44 return 0; 45 } // end main

532 Chapter 10 Classes: A Deeper Look, Part 2 9/13/1999 3/25/2004 9/1/2000 12/14/2004 256 1999 85 2004 245 2000 349 2004 09/13/99 03/25/04 09/01/00 12/14/04 September 13, 1999 March 25, 2004 September 1, 2000 December 14, 2004 Date object destructor for date 12/14/2004 Date object destructor for date 9/1/2000 Date object destructor for date 3/25/2004 Date object destructor for date 9/13/1999 10.8 Create a SavingsAccount class. Use a static data member annualinterestrate to store the annual interest rate for each of the savers. Each member of the class contains a private data member savingsbalance indicating the amount the saver currently has on deposit. Provide member function calculatemonthlyinterest that calculates the monthly interest by multiplying the balance by annualinterestrate divided by 12; this interest should be added to savingsbalance. Provide a static member function modifyinterestrate that sets the static annualinterestrate to a new value. Write a driver program to test class SavingsAccount. Instantiate two different objects of class SavingsAccount, saver1 and saver2, with balances of $2000.00 and $3000.00, respectively. Set the annualinterestrate to 3 percent. Then calculate the monthly interest and print the new balances for each of the savers. Then set the annualinterestrate to 4 percent, calculate the next month s interest and print the new balances for each of the savers. ANS: 1 // SavingsAccount.h 2 // Header file for class SavingsAccount. 3 #ifndef SAVINGS_ACCOUNT_H 4 #define SAVINGS_ACCOUNT_H 5 6 class SavingsAccount 7 { 8 public: 9 // constructor sets balance to value greater than or equal to zero 10 SavingsAccount( double b ) 11 { 12 savingsbalance = ( b >= 0.0? b : 0.0 );

Exercises 533 13 } // end SavingsAccount constructor 14 15 void calculatemonthlyinterest(); // calculate interest; add to balance 16 static void modifyinterestrate( double ); 17 void printbalance() const; 18 private: 19 double savingsbalance; // the account balance 20 static double annualinterestrate; // the interest rate of all accounts 21 }; // end class SavingsAccount 22 23 #endif 1 // Exercise 10.8 Solution: SavingsAccount.cpp 2 // Member-function defintions for class SavingsAccount. 3 #include <iostream> 4 using std::cout; 5 using std::fixed; 6 7 #include <iomanip> 8 using std::setprecision; 9 10 #include "SavingsAccount.h" // SavingsAccount class definition 11 12 // initialize static data member 13 double SavingsAccount::annualInterestRate = 0.0; 14 15 // calculate monthly interest for this savings account 16 void SavingsAccount::calculateMonthlyInterest() 17 { 18 savingsbalance += savingsbalance * ( annualinterestrate / 12.0 ); 19 } // end function calculatemonthlyinterest 20 21 // function for modifying static member variable annualinterestrate 22 void SavingsAccount::modifyInterestRate( double i ) 23 { 24 annualinterestrate = ( i >= 0.0 && i <= 1.0 )? i : 0.03; 25 } // end function modifyinterestrate 26 27 // prints balance of the savings account 28 void SavingsAccount::printBalance() const 29 { 30 cout << fixed << '$' << setprecision( 2 ) << savingsbalance; 31 } // end function printbalance 1 // Exercise 10.8 Solution: ex10_08.cpp 2 // Driver program for class SavingsAccount. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 7 #include <iomanip> 8 using std::setw; 9

534 Chapter 10 Classes: A Deeper Look, Part 2 10 #include "SavingsAccount.h" // SavingsAccount class definition 11 12 int main() 13 { 14 SavingsAccount saver1( 2000.0 ); 15 SavingsAccount saver2( 3000.0 ); 16 17 SavingsAccount::modifyInterestRate(.03 ); // change interest rate 18 19 cout << "Initial balances:\nsaver 1: "; 20 saver1.printbalance(); 21 cout << "\tsaver 2: "; 22 saver2.printbalance(); 23 24 saver1.calculatemonthlyinterest(); 25 saver2.calculatemonthlyinterest(); 26 27 cout << "\n\nbalances after 1 month's interest applied at.03:\n" 28 << "Saver 1: "; 29 saver1.printbalance(); 30 cout << "\tsaver 2: "; 31 saver2.printbalance(); 32 33 SavingsAccount::modifyInterestRate(.04 ); // change interest rate 34 saver1.calculatemonthlyinterest(); 35 saver2.calculatemonthlyinterest(); 36 37 cout << "\n\nbalances after 1 month's interest applied at.04:\n" 38 << "Saver 1: "; 39 saver1.printbalance(); 40 cout << "\tsaver 2: "; 41 saver2.printbalance(); 42 cout << endl; 43 return 0; 44 } // end main Initial balances: Saver 1: $2000.00 Saver 2: $3000.00 Balances after 1 month's interest applied at.03: Saver 1: $2005.00 Saver 2: $3007.50 Balances after 1 month's interest applied at.04: Saver 1: $2011.68 Saver 2: $3017.53 10.9 Create class IntegerSet for which each object can hold integers in the range 0 through 100. A set is represented internally as an array of ones and zeros. Array element a[ i ] is 1 if integer i is in the set. Array element a[ j ] is 0 if integer j is not in the set. The default constructor initializes a set to the so-called empty set, i.e., a set whose array representation contains all zeros. Provide member functions for the common set operations. For example, provide a unionofsets member function that creates a third set that is the set-theoretic union of two existing sets (i.e., an element of the third set s array is set to 1 if that element is 1 in either or both of the existing sets, and an element of the third set s array is set to 0 if that element is 0 in each of the existing sets).

Exercises 535 Provide an intersectionofsets member function which creates a third set which is the settheoretic intersection of two existing sets (i.e., an element of the third set s array is set to 0 if that element is 0 in either or both of the existing sets, and an element of the third set s array is set to 1 if that element is 1 in each of the existing sets). Provide an insertelement member function that inserts a new integer k into a set (by setting a[ k ] to 1). Provide a deleteelement member function that deletes integer m (by setting a[ m ] to 0). Provide a printset member function that prints a set as a list of numbers separated by spaces. Print only those elements that are present in the set (i.e., their position in the array has a value of 1). Print --- for an empty set. Provide an isequalto member function that determines whether two sets are equal. Provide an additional constructor that receives an array of integers and the size of that array and uses the array to initialize a set object. Now write a driver program to test your IntegerSet class. Instantiate several IntegerSet objects. Test that all your member functions work properly. ANS: 1 // Exercise 10.9 Solution: IntegerSet.h 2 // Header file for class IntegerSet 3 #ifndef INTEGER_SET_H 4 #define INTEGER_SET_H 5 6 class IntegerSet 7 { 8 public: 9 // default constructor 10 IntegerSet() 11 { 12 emptyset(); // set all elements of set to 0 13 } // end IntegerSet constructor 14 15 IntegerSet( int [], int ); // constructor that takes an initial set 16 IntegerSet unionofsets( const IntegerSet& ); 17 IntegerSet intersectionofsets( const IntegerSet& ); 18 void emptyset(); // set all elements of set to 0 19 void inputset(); // read values from user 20 void insertelement( int ); 21 void deleteelement( int ); 22 void printset() const; 23 bool isequalto( const IntegerSet& ) const; 24 private: 25 int set[ 101 ]; // range of 0-100 26 27 // determines a valid entry to the set 28 int validentry( int x ) const 29 { 30 return ( x >= 0 && x <= 100 ); 31 } // end function validentry 32 }; // end class IntegerSet 33 34 #endif

536 Chapter 10 Classes: A Deeper Look, Part 2 1 // Exercise 10.9 Solution: IntegerSet.cpp 2 // Member-function definitions for class IntegerSet. 3 #include <iostream> 4 using std::cout; 5 using std::cin; 6 using std::cerr; 7 8 #include <iomanip> 9 using std::setw; 10 11 #include "IntegerSet.h" // IntegerSet class definition 12 13 // constructor creates a set from array of integers 14 IntegerSet::IntegerSet( int array[], int size) 15 { 16 emptyset(); 17 18 for ( int i = 0; i < size; i++ ) 19 insertelement( array[ i ] ); 20 } // end IntegerSet constructor 21 22 // initializes a set to the empty set 23 void IntegerSet::emptySet() 24 { 25 for ( int y = 0; y < 101; y++ ) 26 set[ y ] = 0; 27 } // end function emptyset 28 29 // input a set from the user 30 void IntegerSet::inputSet() 31 { 32 int number; 33 34 do 35 { 36 cout << "Enter an element (-1 to end): "; 37 cin >> number; 38 39 if ( validentry( number ) ) 40 set[ number ] = 1; 41 else if ( number!= -1 ) 42 cerr << "Invalid Element\n"; 43 } while ( number!= -1 ); // end do...while 44 45 cout << "Entry complete\n"; 46 } // end function inputset 47 48 // prints the set to the output stream 49 void IntegerSet::printSet() const 50 { 51 int x = 1; 52 bool empty = true; // assume set is empty 53 54 cout << '{'; 55

Exercises 537 56 for (int u = 0; u < 101; u++ ) 57 { 58 if ( set[ u ] ) 59 { 60 cout << setw( 4 ) << u << ( x % 10 == 0? "\n" : "" ); 61 empty = false; // set is not empty 62 x++; 63 } // end if 64 } // end for 65 66 if ( empty ) 67 cout << setw( 4 ) << "---"; // display an empty set 68 69 cout << setw( 4 ) << "}" << '\n'; 70 } // end function printset 71 72 // returns the union of two sets 73 IntegerSet IntegerSet::unionOfSets( const IntegerSet &r ) 74 { 75 IntegerSet temp; 76 77 // if element is in either set, add to temporary set 78 for ( int n = 0; n < 101; n++ ) 79 if ( set[ n ] == 1 r.set[ n ] == 1 ) 80 temp.set[ n ] = 1; 81 82 return temp; 83 } // end function unionofsets 84 85 // returns the intersection of two sets 86 IntegerSet IntegerSet::intersectionOfSets( const IntegerSet &r ) 87 { 88 IntegerSet temp; 89 90 // if element is in both sets, add to temporary set 91 for ( int w = 0; w < 101; w++ ) 92 if ( set[ w ] == 1 && r.set[ w ] == 1 ) 93 temp.set[ w ] = 1; 94 95 return temp; 96 } // end function intersectionofsets 97 98 // insert a new integer into this set 99 void IntegerSet::insertElement( int k ) 100 { 101 if ( validentry( k ) ) 102 set[ k ] = 1; 103 else 104 cerr << "Invalid insert attempted!\n"; 105 } // end function insertelement 106 107 // removes an integer from this set 108 void IntegerSet::deleteElement( int m ) 109 { 110 if ( validentry( m ) )

538 Chapter 10 Classes: A Deeper Look, Part 2 111 set[ m ] = 0; 112 else 113 cerr << "Invalid delete attempted!\n"; 114 } // end function deleteelement 115 116 // determines if two sets are equal 117 bool IntegerSet::isEqualTo( const IntegerSet &r ) const 118 { 119 for ( int v = 0; v < 101; v++ ) 120 if ( set[ v ]!= r.set[ v ] ) 121 return false; // sets are not-equal 122 123 return true; // sets are equal 124 } // end function isequalto 1 // Exercise 10.9 Solution: ex10_09.cpp 2 // Driver program for class IntegerSet. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 7 #include "IntegerSet.h" // IntegerSet class definition 8 9 int main() 10 { 11 IntegerSet a; 12 IntegerSet b; 13 IntegerSet c; 14 IntegerSet d; 15 16 cout << "Enter set A:\n"; 17 a.inputset(); 18 cout << "\nenter set B:\n"; 19 b.inputset(); 20 c = a.unionofsets( b ); 21 d = a.intersectionofsets( b ); 22 cout << "\nunion of A and B is:\n"; 23 c.printset(); 24 cout << "Intersection of A and B is:\n"; 25 d.printset(); 26 27 if ( a.isequalto( b ) ) 28 cout << "Set A is equal to set B\n"; 29 else 30 cout << "Set A is not equal to set B\n"; 31 32 cout << "\ninserting 77 into set A...\n"; 33 a.insertelement( 77 ); 34 cout << "Set A is now:\n"; 35 a.printset(); 36 37 cout << "\ndeleting 77 from set A...\n"; 38 a.deleteelement( 77 ); 39 cout << "Set A is now:\n";

Exercises 539 40 a.printset(); 41 42 const int arraysize = 10; 43 int intarray[ arraysize ] = { 25, 67, 2, 9, 99, 105, 45, -5, 100, 1 }; 44 IntegerSet e( intarray, arraysize ); 45 46 cout << "\nset e is:\n"; 47 e.printset(); 48 49 cout << endl; 50 51 return 0; 52 } // end main Enter set A: Enter an element (-1 to end): 45 Enter an element (-1 to end): 76 Enter an element (-1 to end): 34 Enter an element (-1 to end): 6 Enter an element (-1 to end): -1 Entry complete Enter set B: Enter an element (-1 to end): 34 Enter an element (-1 to end): 8 Enter an element (-1 to end): 93 Enter an element (-1 to end): 45 Enter an element (-1 to end): -1 Entry complete Union of A and B is: { 6 8 34 45 76 93 } Intersection of A and B is: { 34 45 } Set A is not equal to set B Inserting 77 into set A... Set A is now: { 6 34 45 76 77 } Deleting 77 from set A... Set A is now: { 6 34 45 76 } Invalid insert attempted! Invalid insert attempted! Set e is: { 1 2 9 25 45 67 99 100 } 10.10 It would be perfectly reasonable for the Time class of Figs. 10.18 10.19 to represent the time internally as the number of seconds since midnight rather than the three integer values hour, minute and second. Clients could use the same public methods and get the same results. Modify

540 Chapter 10 Classes: A Deeper Look, Part 2 the Time class of Fig. 10.18 to implement the time as the number of seconds since midnight and show that there is no visible change in functionality to the clients of the class. [Note: This exercise nicely demonstrates the virtues of implementation hiding.] ANS: 1 // Exercise 10.10 Solution: Time.h 2 // Time class definition; Member functions defined in Time.cpp. 3 #ifndef TIME_H 4 #define TIME_H 5 6 class Time 7 { 8 public: 9 Time( int = 0, int = 0, int = 0 ); // default constructor 10 11 // set functions (the Time & return types enable cascading) 12 Time &settime( int, int, int ); // set hour, minute, second 13 Time &sethour( int ); // set hour 14 Time &setminute( int ); // set minute 15 Time &setsecond( int ); // set second 16 17 // get functions (normally declared const) 18 int gethour() const; // return hour 19 int getminute() const; // return minute 20 int getsecond() const; // return second 21 22 // print functions (normally declared const) 23 void printuniversal() const; // print universal time 24 void printstandard() const; // print standard time 25 private: 26 int totalseconds; // number of seconds since midnight 27 }; // end class Time 28 29 #endif 1 // Exercise 10.10 Solution: Time.cpp 2 // Member-function definitions for Time class. 3 #include <iostream> 4 using std::cout; 5 6 #include <iomanip> 7 using std::setfill; 8 using std::setw; 9 10 #include "Time.h" // Time class definition 11 12 // constructor function to initialize private data; 13 // calls member function settime to set variables; 14 // default values are 0 (see class definition) 15 Time::Time( int hr, int min, int sec ) 16 { 17 settime( hr, min, sec ); 18 } // end Time constructor

Exercises 541 19 20 // set values of hour, minute, and second 21 Time &Time::setTime( int h, int m, int s ) // note Time & return 22 { 23 sethour( h ); 24 setminute( m ); 25 setsecond( s ); 26 return *this; // enables cascading 27 } // end function settime 28 29 // set hour value 30 Time &Time::setHour( int h ) // note Time & return 31 { 32 int hours = ( h >= 0 && h < 24 )? h : 0; 33 totalseconds = ( hours * 3600 ) + ( getminute() * 60 ) + getsecond(); 34 return *this; // enables cascading 35 } // end function sethour 36 37 // set minute value 38 Time &Time::setMinute( int m ) // note Time & return 39 { 40 int minutes = ( m >= 0 && m < 60 )? m : 0; 41 totalseconds = ( gethour() * 3600 ) + ( minutes * 60 ) + getsecond(); 42 return *this; // enables cascading 43 } // end function setminute 44 45 // set second value 46 Time &Time::setSecond( int s ) // note Time & return 47 { 48 int seconds = ( s >= 0 && s < 60 )? s : 0; 49 totalseconds = ( gethour() * 3600 ) + ( getminute() * 60 ) + seconds; 50 return *this; // enables cascading 51 } // end function setsecond 52 53 // get hour value 54 int Time::getHour() const 55 { 56 return ( totalseconds / 3600 ); 57 } // end function gethour 58 59 // get minute value 60 int Time::getMinute() const 61 { 62 return ( ( totalseconds % 3600 ) / 60 ); 63 } // end function getminute 64 65 // get second value 66 int Time::getSecond() const 67 { 68 return ( ( totalseconds % 3600 ) % 60 ); 69 } // end function getsecond 70 71 // print Time in universal-time format (HH:MM:SS) 72 void Time::printUniversal() const 73 {

542 Chapter 10 Classes: A Deeper Look, Part 2 74 cout << setfill( '0' ) << setw( 2 ) << gethour() << ":" 75 << setw( 2 ) << getminute() << ":" << setw( 2 ) << getsecond(); 76 } // end function printuniversal 77 78 // print Time in standard-time format (HH:MM:SS AM or PM) 79 void Time::printStandard() const 80 { 81 int hour = gethour(); 82 cout << ( ( hour == 0 hour == 12 )? 12 : hour % 12 ) 83 << ":" << setfill( '0' ) << setw( 2 ) << getminute() 84 << ":" << setw( 2 ) << getsecond() << ( hour < 12? " AM" : " PM" ); 85 } // end function printstandard 1 // Exercise 10.10 Solution: ex10_10.cpp 2 // Driver program for Time class. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 7 #include "Time.h" // Time class definition 8 9 int main() 10 { 11 Time t; // create Time object 12 13 // cascaded function calls 14 t.sethour( 18 ).setminute( 30 ).setsecond( 22 ); 15 16 // output time in universal and standard formats 17 cout << "Universal time: "; 18 t.printuniversal(); 19 20 cout << "\nstandard time: "; 21 t.printstandard(); 22 23 cout << "\n\nnew standard time: "; 24 25 // cascaded function calls 26 t.settime( 20, 20, 20 ).printstandard(); 27 cout << endl; 28 return 0; 29 } // end main Universal time: 18:30:22 Standard time: 6:30:22 PM New standard time: 8:20:20 PM