Classes: A Deeper Look, Part 2

Size: px
Start display at page:

Download "Classes: A Deeper Look, Part 2"

Transcription

1 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.

2 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 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;

3 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 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 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 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 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 Modify class Date in Fig 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).

4 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 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 // 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 #endif 1 // Exercise 10.7 Solution: Date.cpp 2 // Member-function definitions for class Date. 3 #include <iostream>

5 Exercises using std::cout; 5 using std::endl; 6 7 #include <iomanip> 8 using std::setw; 9 using std::setfill; #include <ctime> 12 using std::time; 13 using std::localtime; 14 using std::tm; 15 using std::time_t; #include "Date.h" // include Date class definition // 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; time_t t = time( 0 ); // determine current calendar time // convert current calendar time pointed to by t into 28 // broken down time and assign it to ptr 29 ptr = localtime( &t ); 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 ; // broken down year since } // end Date constructor // 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 // 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 // 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

6 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 // 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 // print Date object in form: month/day/year 78 void Date::print() const 79 { 80 cout << month << '/' << day << '/' << year << endl; 81 } // end function print // print Date object in form: ddd yyyy 84 void Date::printDDDYYYY() const 85 { 86 cout << convertddtoddd() << ' ' << year << endl; 87 } // end function printdddyyyy // 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 // 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 // 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 // utility function to confirm proper day value based on 113 // month and year; handles leap years, too

7 Exercises 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; // February 29 check for leap year 121 if ( month == 2 && testday == 29 && isleapyear() ) 122 return testday; cout << "Invalid day (" << testday << ") set to 1.\n"; 125 return 1; // leave object in consistent state if bad value 126 } // end function checkday // return the number of days in a month 129 int Date::daysInMonth( int m ) const 130 { 131 if ( isleapyear() && m == 2 ) 132 return 29; static const int dayspermonth[ 13 ] = 135 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dayspermonth[ m ]; 138 } // end function daysinmonth // 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 // calculate 3-digit day based on Date object's current month and day 150 int Date::convertDDToDDD() const 151 { 152 int ddd = 0; // for each month that has passed, add days to ddd 155 for ( int i = 1; i < month; i++ ) 156 ddd += daysinmonth( i ); // add days from current month 159 ddd += day; return ddd; 162 } // end function convertddtoddd // set month and day based on 3-digit day 165 void Date::setMMDDFromDDD( int ddd ) 166 { 167 int daytotal = 0; 168 int m;

8 530 Chapter 10 Classes: A Deeper Look, Part for ( m = 1; m <= 12 && ( daytotal + daysinmonth( m ) ) < ddd; m++ ) 171 daytotal += daysinmonth( m ); setmonth( m ); 174 setday( ddd - daytotal ); 175 } // end function setmmddfromddd // 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" }; return months[ mm ]; 185 } // end function convertmmtomonth // set month number based on month name 188 void Date::setMMFromMonth( string m ) 189 { 190 bool matchfound = false; // loop for each month, checking for a match 193 for ( int i = 1; i <= 12 &&!matchfound; i++ ) 194 { 195 string tempmonth = convertmmtomonth( i ); if ( tempmonth == m ) 198 { 199 setmonth( i ); 200 matchfound = true; 201 } // end if 202 } // end for 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 // utility function to convert 4-digit year to 2-digit year 212 int Date::convertYYYYToYY() const 213 { 214 // if year is in 2000s, subtract // else, assume year is in the 1900s and subtract return ( year >= 2000? year : year ); 217 } // end function convertyyyytoyy // 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

9 Exercises year = ( yy < 7? yy : yy ); 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 // print Date objects in default format 17 date1.print(); 18 date2.print(); 19 date3.print(); 20 date4.print(); 21 cout << '\n'; // print Date objects in 'ddd yyyy' format 24 date1.printdddyyyy(); 25 date2.printdddyyyy(); 26 date3.printdddyyyy(); 27 date4.printdddyyyy(); 28 cout << '\n'; // print Date objects in 'mm/dd/yy' format 31 date1.printmmddyy(); 32 date2.printmmddyy(); 33 date3.printmmddyy(); 34 date4.printmmddyy(); 35 cout << '\n'; // print Date objects in '"month" d, yyyy' format 38 date1.printmonthddyyyy(); 39 date2.printmonthddyyyy(); 40 date3.printmonthddyyyy(); 41 date4.printmonthddyyyy(); 42 cout << endl; return 0; 45 } // end main

10 532 Chapter 10 Classes: A Deeper Look, Part 2 9/13/1999 3/25/2004 9/1/ /14/ /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/ 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 $ and $ , 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 );

11 Exercises } // end SavingsAccount constructor 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 #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 // initialize static data member 13 double SavingsAccount::annualInterestRate = 0.0; // calculate monthly interest for this savings account 16 void SavingsAccount::calculateMonthlyInterest() 17 { 18 savingsbalance += savingsbalance * ( annualinterestrate / 12.0 ); 19 } // end function calculatemonthlyinterest // 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 // 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

12 534 Chapter 10 Classes: A Deeper Look, Part 2 10 #include "SavingsAccount.h" // SavingsAccount class definition int main() 13 { 14 SavingsAccount saver1( ); 15 SavingsAccount saver2( ); SavingsAccount::modifyInterestRate(.03 ); // change interest rate cout << "Initial balances:\nsaver 1: "; 20 saver1.printbalance(); 21 cout << "\tsaver 2: "; 22 saver2.printbalance(); saver1.calculatemonthlyinterest(); 25 saver2.calculatemonthlyinterest(); 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(); SavingsAccount::modifyInterestRate(.04 ); // change interest rate 34 saver1.calculatemonthlyinterest(); 35 saver2.calculatemonthlyinterest(); 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: $ Saver 2: $ Balances after 1 month's interest applied at.03: Saver 1: $ Saver 2: $ Balances after 1 month's interest applied at.04: Saver 1: $ Saver 2: $ 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).

13 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 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 // 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 #endif

14 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; #include "IntegerSet.h" // IntegerSet class definition // constructor creates a set from array of integers 14 IntegerSet::IntegerSet( int array[], int size) 15 { 16 emptyset(); for ( int i = 0; i < size; i++ ) 19 insertelement( array[ i ] ); 20 } // end IntegerSet constructor // 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 // input a set from the user 30 void IntegerSet::inputSet() 31 { 32 int number; do 35 { 36 cout << "Enter an element (-1 to end): "; 37 cin >> number; if ( validentry( number ) ) 40 set[ number ] = 1; 41 else if ( number!= -1 ) 42 cerr << "Invalid Element\n"; 43 } while ( number!= -1 ); // end do...while cout << "Entry complete\n"; 46 } // end function inputset // 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 cout << '{'; 55

15 Exercises 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 if ( empty ) 67 cout << setw( 4 ) << "---"; // display an empty set cout << setw( 4 ) << "}" << '\n'; 70 } // end function printset // returns the union of two sets 73 IntegerSet IntegerSet::unionOfSets( const IntegerSet &r ) 74 { 75 IntegerSet temp; // 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; return temp; 83 } // end function unionofsets // returns the intersection of two sets 86 IntegerSet IntegerSet::intersectionOfSets( const IntegerSet &r ) 87 { 88 IntegerSet temp; // 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; return temp; 96 } // end function intersectionofsets // 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 // removes an integer from this set 108 void IntegerSet::deleteElement( int m ) 109 { 110 if ( validentry( m ) )

16 538 Chapter 10 Classes: A Deeper Look, Part set[ m ] = 0; 112 else 113 cerr << "Invalid delete attempted!\n"; 114 } // end function deleteelement // 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 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; 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(); 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"; cout << "\ninserting 77 into set A...\n"; 33 a.insertelement( 77 ); 34 cout << "Set A is now:\n"; 35 a.printset(); cout << "\ndeleting 77 from set A...\n"; 38 a.deleteelement( 77 ); 39 cout << "Set A is now:\n";

17 Exercises a.printset(); const int arraysize = 10; 43 int intarray[ arraysize ] = { 25, 67, 2, 9, 99, 105, 45, -5, 100, 1 }; 44 IntegerSet e( intarray, arraysize ); cout << "\nset e is:\n"; 47 e.printset(); cout << endl; 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: { } Intersection of A and B is: { } Set A is not equal to set B Inserting 77 into set A... Set A is now: { } Deleting 77 from set A... Set A is now: { } Invalid insert attempted! Invalid insert attempted! Set e is: { } It would be perfectly reasonable for the Time class of Figs 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

18 540 Chapter 10 Classes: A Deeper Look, Part 2 the Time class of Fig 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 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 // 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 // get functions (normally declared const) 18 int gethour() const; // return hour 19 int getminute() const; // return minute 20 int getsecond() const; // return second // 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 #endif 1 // Exercise 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 // 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

19 Exercises // 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 // 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 // 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 // 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 // get hour value 54 int Time::getHour() const 55 { 56 return ( totalseconds / 3600 ); 57 } // end function gethour // get minute value 60 int Time::getMinute() const 61 { 62 return ( ( totalseconds % 3600 ) / 60 ); 63 } // end function getminute // get second value 66 int Time::getSecond() const 67 { 68 return ( ( totalseconds % 3600 ) % 60 ); 69 } // end function getsecond // print Time in universal-time format (HH:MM:SS) 72 void Time::printUniversal() const 73 {

20 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 // 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 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 // cascaded function calls 14 t.sethour( 18 ).setminute( 30 ).setsecond( 22 ); // output time in universal and standard formats 17 cout << "Universal time: "; 18 t.printuniversal(); cout << "\nstandard time: "; 21 t.printstandard(); cout << "\n\nnew standard time: "; // 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

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>

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> CISC11 Introduction to Computer Science Dr. McCoy Lecture 20 November, 2009. Using Default Arguments with Constructors Constructors Can specify default arguments Default constructors Defaults all arguments

More information

Computer Programming with C++ (21)

Computer Programming with C++ (21) Computer Programming with C++ (21) Zhang, Xinyu Department of Computer Science and Engineering, Ewha Womans University, Seoul, Korea zhangxy@ewha.ac.kr Classes (III) Chapter 9.7 Chapter 10 Outline Destructors

More information

Classes: A Deeper Look. Systems Programming

Classes: A Deeper Look. Systems Programming Classes: A Deeper Look Systems Programming Deeper into C++ Classes const objects and const member functions Composition Friendship this pointer Dynamic memory management new and delete operators static

More information

A Deeper Look at Classes

A Deeper Look at Classes A Deeper Look at Classes Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by

More information

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

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 CHAPTER 7 CLASSES: PART II 1 Illustrations List (Main Page) 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 Using a Time class with const objects and const member

More information

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

W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls 1 W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls 2 7.4 friend Functions and friend Classes friend function and friend classes Can access private

More information

Computer Programming Class Members 9 th Lecture

Computer Programming Class Members 9 th Lecture Computer Programming Class Members 9 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 Eom, Hyeonsang All Rights Reserved Outline Class

More information

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

Angela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan. C++ Classes: Part II Angela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 17.2 const (Constant) Objects and

More information

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

Pointer Assignments. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 18 October 29, The new Operator CISC11 Introduction to Computer Science Dr. McCoy Lecture 1 October 29, 2009 Pointer Assignments Pointer variables can be "assigned": int *p1, *p2; p2 = p1; Assigns one pointer to another "Make p2 point

More information

Chapter 17 - C++ Classes: Part II

Chapter 17 - C++ Classes: Part II Chapter 17 - C++ Classes: Part II 17.1 Introduction 17.2 const (Constant) Objects and const Member Functions 17.3 Composition: Objects as Members of Classes 17.4 friend Functions and friend Classes 17.5

More information

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

Preview 11/1/2017. Constant Objects and Member Functions. Constant Objects and Member Functions. Constant Objects and Member Functions Preview Constant Objects and Constant Functions Composition: Objects as Members of a Class Friend functions The use of Friend Functions Some objects need to be modifiable and some do not. A programmer

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Chapter 17 - C++ Classes: Part II 17.1 Introduction 17.2 const (Constant) Objects and const Member Functions 17.3 Composition: Objects as Members of Classes 17.4 friend

More information

Classes: A Deeper Look, Part 1

Classes: A Deeper Look, Part 1 9 Classes: A Deeper Look, Part 1 OBJECTIVES In this chapter you will learn: How to use a preprocessor wrapper to prevent multiple definition errors caused by including more than one copy of a header file

More information

Chapter 6: Classes and Data Abstraction

Chapter 6: Classes and Data Abstraction Chapter 6: Classes and Data Abstraction 1 6.1 Introduction 6.2 Structure Definitions 6.3 Accessing Structure Members 6.4 Implementing a User-Defined Type Time with a struct 6.5 Implementing a Time Abstract

More information

Classes: A Deeper Look

Classes: A Deeper Look Classes: A Deeper Look 1 Introduction Implementing a Time Abstract Data Type with a class Class Scope and Accessing Class Members Separating Interface from Implementation Controlling Access to Members

More information

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

9.1 Introduction. Integrated Time class case study Preprocessor wrapper Three types of handles on an object. Class functions 1 9 Classes: A Deeper Look, Part 1 OBJECTIVES In this chapter you ll learn: How to use a preprocessor p wrapper to prevent multiple definition errors caused by including more than one copy of a header

More information

57:017, Computers in Engineering C++ Classes

57:017, Computers in Engineering C++ Classes 57:017, Computers in Engineering C++ Classes Copyright 1992 2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Introduction Object-oriented programming (OOP) Encapsulates

More information

More C++ Classes. Systems Programming

More C++ Classes. Systems Programming More C++ Classes Systems Programming C++ Classes Preprocessor Wrapper Time Class Case Study Class Scope and Assessing Class Members Using handles to access class members Access and Utility Functions Destructors

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3: Classes May 24, 2004 2 Classes Structure Definitions 3 Structures Aggregate data types built using elements of other

More information

Introduction to Programming session 24

Introduction to Programming session 24 Introduction to Programming session 24 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel sslides Sharif Universityof Technology Outlines Introduction

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 5: Classes September 14, 2004 Structure Definitions 2 Structures Aggregate data types built using elements of other types

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3 Jan 20, 2004 Quiz 1 2 Average: about 3.8 More than half obtained: 4 + Highest is 8 Need more work/practice! Quiz 1

More information

Chapter 16: Classes and Data Abstraction

Chapter 16: Classes and Data Abstraction Chapter 16: Classes and Data Abstraction 16.1 Introduction 16.2 Implementing a Time Abstract Data Type with a Class 16.3 Class Scope and Accessing Class Members 16.4 Separating Interface from Implementation

More information

Classes and Objects: A Deeper Look

Classes and Objects: A Deeper Look 8 Instead of this absurd division into sexes, they ought to class people as static and dynamic. Evelyn Waugh Is it a world to hide virtues in? William Shakespeare But what, to serve our private ends, Forbids

More information

Chapter 9 Classes : A Deeper Look, Part 1

Chapter 9 Classes : A Deeper Look, Part 1 Chapter 9 Classes : A Deeper Look, Part 1 C++, How to Program Deitel & Deitel Fall 2016 CISC1600 Yanjun Li 1 Time Class Case Study Time Class Definition: private data members: int hour; int minute; int

More information

Fundamentals of Programming Session 24

Fundamentals of Programming Session 24 Fundamentals of Programming Session 24 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Classes and Data Abstraction. Topic 5

Classes and Data Abstraction. Topic 5 Classes and Data Abstraction Topic 5 Classes Class User Defined Data Type Object Variable Data Value Operations Member Functions Object Variable Data Value Operations Member Functions Object Variable Data

More information

Operator Overloading

Operator Overloading Operator Overloading Introduction Operator overloading Enabling C++ s operators to work with class objects Using traditional operators with user-defined objects Requires great care; when overloading is

More information

Classes and Objects: A Deeper Look

Classes and Objects: A Deeper Look 1 8 Classes and Objects: A Deeper Look 1 // Fig. 8.1: Time1.java 2 // Time1 class declaration maintains the time in 24-hour format. 4 public class Time1 6 private int hour; // 0 2 7 private int minute;

More information

W8.2 Operator Overloading

W8.2 Operator Overloading 1 W8.2 Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. as friend Functions Overloading Stream Insertion and Extraction

More information

Introduction. W8.2 Operator Overloading

Introduction. W8.2 Operator Overloading W8.2 Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. as friend Functions Overloading Stream Insertion and Extraction

More information

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

Deitel Dive-Into Series: Dive-Into Cygwin and GNU C++ 1 Deitel Dive-Into Series: Dive-Into Cygwin and GNU C++ Objectives To be able to use Cygwin, a UNIX simulator. To be able to use a text editor to create C++ source files To be able to use GCC to compile

More information

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2

More information

CS 1337 Computer Science II Page 1

CS 1337 Computer Science II Page 1 Source File: ~/1337/65/lab65.(C CPP cpp c++ cc cxx cp) Input: Under control of main function Output: Under control of main function Value: 3 The purpose of this assignment is to add to the implementation

More information

Chapter 7: Classes Part II

Chapter 7: Classes Part II 1 Chapter 7: Classes Part II 7.1 Introduction 7.2 const (Constant) Objects and const Member Functions 7.3 Composition: Objects a s Members of Cla sses 7.4 friend Func tions a nd friend Cla sse s 7.5 Using

More information

Operator Overloading

Operator Overloading Operator Overloading Introduction Operator overloading Enabling C++ s operators to work with class objects Using traditional operators with user-defined objects Requires great care; when overloading is

More information

Classes and Objects: A Deeper Look

Classes and Objects: A Deeper Look Classes and Objects: A Deeper Look 8 Instead of this absurd division into sexes, they ought to class people as static and dynamic. Evelyn Waugh Is it a world to hide virtues in? William Shakespeare But

More information

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

Preview 9/20/2017. Object Oriented Programing with C++ Object Oriented Programing with C++ Object Oriented Programing with C++ Preview Object Oriented Programming with C++ Class Members Inline Functions vs. Regular Functions Constructors & Destructors Initializing class Objects with Constructors C++ Programming Language C Programming

More information

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

Homework 3. Due: Feb 25, 23:59pm. Section 1 (20 pts, 2 pts each) Multiple Choice Questions Homework 3 Due: Feb 25, 23:59pm Section 1 (20 pts, 2 pts each) Multiple Choice Questions Q1: A function that modifies an array by using pointer arithmetic such as ++ptr to process every value of the array

More information

Operator Overloading

Operator Overloading Steven Zeil November 4, 2013 Contents 1 Operators 2 1.1 Operators are Functions.... 2 2 I/O Operators 4 3 Comparison Operators 6 3.1 Equality Operators....... 11 3.2 Less-Than Operators...... 13 1 1 Operators

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism 1 Inheritance extending a clock to an alarm clock deriving a class 2 Polymorphism virtual functions and polymorphism abstract classes MCS 360 Lecture 8 Introduction to Data

More information

Operator Overloading in C++ Systems Programming

Operator Overloading in C++ Systems Programming Operator Overloading in C++ Systems Programming Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. Global Functions Overloading

More information

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

clarity. In the first form, the access specifier public : is needed to { Structure Time CSC 211 Intermediate Programming Classes in C++ // Create a structure, set its members, and print it. struct Time // structure definition int hour; // 0-23 int minute; // 0-59 int second;

More information

Fundamentals of Programming Session 25

Fundamentals of Programming Session 25 Fundamentals of Programming Session 25 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

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

Encapsulation. Contents. Steven Zeil. July 17, Encapsulation Encapsulation in C Classes 4. 3 Hiding Attributes 8 Steven Zeil July 17, 2013 Contents 1 Encapsulation 2 1.1 Encapsulation in C++........................................................ 2 2 Classes 4 3 Hiding Attributes 8 4 Inline Functions 11 4.1 How Functions

More information

Classes and Data Abstraction

Classes and Data Abstraction 6 Classes and Data Abstraction Objectives To understand the software engineering concepts of encapsulation and data hiding. To understand the notions of data abstraction and abstract data types (ADTs).

More information

! 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. Classes and Objects Week 5 Gaddis:.2-.12 14.3-14.4 CS 5301 Spring 2015 Jill Seaman The Class! A class in C++ is similar to a structure.! A class contains members: - variables AND - functions (often called

More information

! 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. Classes and Objects Week 5 Gaddis:.2-.12 14.3-14.4 CS 5301 Fall 2016 Jill Seaman The Class! A class in C++ is similar to a structure.! A class contains members: - variables AND - functions (often called

More information

Chapter 18 - C++ Operator Overloading

Chapter 18 - C++ Operator Overloading Chapter 18 - C++ Operator Overloading Outline 18.1 Introduction 18.2 Fundamentals of Operator Overloading 18.3 Restrictions on Operator Overloading 18.4 Operator Functions as Class Members vs. as friend

More information

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

CIS 190: C/C++ Programming. Classes in C++ CIS 190: C/C++ Programming Classes in C++ Outline Header Protection Functions in C++ Procedural Programming vs OOP Classes Access Constructors Headers in C++ done same way as in C including user.h files:

More information

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

l A class in C++ is similar to a structure. l A class contains members: - variables AND - public: accessible outside the class. Classes and Objects Week 5 Gaddis:.2-.12 14.3-14.4 CS 5301 Spring 2018 Jill Seaman The Class l A class in C++ is similar to a structure. l A class contains members: - variables AND - functions (often called

More information

! 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 Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Spring 2013 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform

More information

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

An inline function is one in which the function code replaces the function call directly. Inline class member functions Inline Functions An inline function is one in which the function code replaces the function call directly. Inline class member functions if they are defined as part of the class definition, implicit if

More information

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

Do not turn to the next page until the start of the exam. Introduction to Programming, PIC10A E. Ryu Fall 2017 Midterm Exam Friday, November 3, 2017 50 minutes, 11 questions, 100 points, 8 pages While we don t expect you will need more space than provided, you

More information

Classes and Data Abstraction. Topic 5

Classes and Data Abstraction. Topic 5 Classes and Data Abstraction Topic 5 Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes The data and functions of a class

More information

! 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 Ch 13: Introduction to Classes 13.1 Procedural Programming Data is stored in variables CS 2308 Spring 2014 Jill Seaman - Perhaps using arrays and structs. Program is a collection of functions that perform

More information

Operator Overloading

Operator Overloading Steven Zeil November 4, 2013 Contents 1 Operators 2 1.1 Operators are Functions...................................................... 2 2 I/O Operators 4 3 Comparison Operators 38 3.1 Equality Operators.........................................................

More information

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

The Class. Classes and Objects. Example class: Time class declaration with functions defined inline. Using Time class in a driver. Classes and Objects Week 5 Gaddis:.2-.12 14.3-14.4 CS 5301 Fall 2014 Jill Seaman The Class A class in C++ is similar to a structure. A class contains members: - variables AND - functions (often called

More information

! 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 Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Fall 2012 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform

More information

! 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 Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Fall 2013 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform

More information

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

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 Introduction to Classes 13.2 The Class Unit 4 Chapter 13 CS 2308 Fall 2016 Jill Seaman 1 l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains

More information

! 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 Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Spring 2015 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform

More information

1 OBJECT-BASED PROGRAMMING CHAPTER 8

1 OBJECT-BASED PROGRAMMING CHAPTER 8 1 OBJECT-BASED PROGRAMMING CHAPTER 8 8 Object-Based Programming 1 // Fig. 8.1: Time1.java 2 // Time1 class definition 3 import java.text.decimalformat; // used for number formatting 4 5 // This class maintains

More information

Arrays. Week 4. Assylbek Jumagaliyev

Arrays. Week 4. Assylbek Jumagaliyev Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays

More information

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

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

Software Design Abstract Data Types

Software Design Abstract Data Types Software Design Abstract Data Types 1 Software Design top down, bottom up, object-oriented abstract data types 2 Specifying a ClassClock date and time in a C++ program encapsulating C code public and private

More information

Assignment 2 Solution

Assignment 2 Solution Assignment 2 Solution Date.h #ifndef DATE_H #define DATE_H #include class Date time_t date; public: Date(); Date(const Date&) = default; Date(time_t); // Date in time_t format Date(const char*);

More information

Object Oriented Design

Object Oriented Design Object Oriented Design Chapter 9 Initializing a non-static data member in the class definition is a syntax error 1 9.2 Time Class Case Study In Fig. 9.1, the class definition is enclosed in the following

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

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

this Pointer, Constant Functions, Static Data Members, and Static Member Functions this Pointer (11.1) Example of this pointer this Pointer, Constant Functions, Static Data Members, and Static Member Functions 3/2/07 CS250 Introduction to Computer Science II 1 this Pointer (11.1) functions - only one copy of each function exists

More information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2305/lab06.(C CPP cpp c++ cc cxx cp) Input: Under control of main function Output: Under control of main function Value: 2 Extend the IntegerSet class from Lab 04 to provide the following

More information

CSCI-1200 Data Structures Fall 2018 Lecture 3 Classes I

CSCI-1200 Data Structures Fall 2018 Lecture 3 Classes I Review from Lecture 2 CSCI-1200 Data Structures Fall 2018 Lecture 3 Classes I Vectors are dynamically-sized arrays Vectors, strings and other containers should be: passed by reference when they are to

More information

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

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 1 ARRAYS Arrays 2 Arrays Structures of related data items Static entity (same size

More information

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

Classes and Objects. Types and Classes. Example. Object Oriented Programming Classes and Objects Types and Classes Chapter 6 Object Oriented program development. Read this Chapter 7 Classes Read this Chapter 8 More About Classes Some sections will be assigned later Chapter 9 Inheritance.

More information

Practice Problems CS2620 Advanced Programming, Spring 2003

Practice Problems CS2620 Advanced Programming, Spring 2003 Practice Problems CS2620 Advanced Programming, Spring 2003 April 9, 2003 1. Explain the results of each vector definition: string pals[] = "pooh", "tigger", "piglet", "eeyore", "kanga" a) vector

More information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2315/11/lab11.(C CPP cpp c++ cc cxx cp) Input: Under control of main function Output: Under control of main function Value: 1 The purpose of this assignment is to become more familiar with

More information

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

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples. Outline Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples. 1 Arrays I Array One type of data structures. Consecutive group of memory locations

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

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

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 Introduction to Classes 13.2 The Class Unit 4 Chapter 13 CS 2308 Spring 2017 Jill Seaman 1 l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains

More information

Classes and Objects:A Deeper Look

Classes and Objects:A Deeper Look www.thestudycampus.com Classes and Objects:A Deeper Look O b j e c t i v e s In this chapter you ll learn: Encapsulation and data hiding. To use keywordthis. To usestatic variables and methods. To importstatic

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

Lecture 5. Function Pointers

Lecture 5. Function Pointers Lecture 5 Pointers to functions Complicated declarations Allocating and deallocating memory Classes const member functions Constructors and destructor this pointer static members Templates Lec 5 Programming

More information

Object-Based Programming

Object-Based Programming Object-Based Programming 8.1 Introduction 8.2 Implementing a Time Abstract Data Type with a Class 8.3 Class Scope 8.4 Controlling Access to Members 8.5 Creating Packages 8.6 Initializing Class Objects:

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Operator Overloading, Inheritance Lecture 6 February 10, 2005 Fundamentals of Operator Overloading 2 Use operators with objects

More information

Programming Assignment #2

Programming Assignment #2 Programming Assignment #2 Due: 11:59pm, Wednesday, Feb. 13th Objective: This assignment will provide further practice with classes and objects, and deepen the understanding of basic OO programming. Task:

More information

Operator overloading: extra examples

Operator overloading: extra examples Operator overloading: extra examples CS319: Scientific Computing (with C++) Niall Madden Week 8: some extra examples, to supplement what was covered in class 1 Eg 1: Points in the (x, y)-plane Overloading

More information

6.096 Introduction to C++

6.096 Introduction to C++ MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. MASSACHUSETTS INSTITUTE

More information

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

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types Chapter 4 - Arrays 1 4.1 Introduction 4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using

More information

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

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public

More information

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

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual

More information

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

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1 C How to Program, 6/e 1 Structures : Aggregate data types are built using elements of other types struct Time { int hour; int minute; Members of the same structure must have unique names. Two different

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

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

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011 Print Your Name: Page 1 of 8 Signature: Aludra Loginname: CSCI 102L - Data Structures Midterm Exam #1 Fall 2011 (10:00am - 11:12am, Wednesday, October 5) Instructor: Bill Cheng Problems Problem #1 (24

More information

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

Ich habe in allen Klassen konsequent ClassInvariant umgesetzt, als Beispiel dient hier eine der komplexeren Versionen, nämlich die in CHouse: Dokumentation Ich habe in allen Klassen konsequent ClassInvariant umgesetzt, als Beispiel dient hier eine der komplexeren Versionen, nämlich die in CHouse: // validate a house bool CHouse::ClassInvariant()

More information

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

Unit Testing. Contents. Steven Zeil. July 22, Types of Testing 2. 2 Unit Testing Scaffolding Drivers Stubs... Steven Zeil July 22, 2013 Contents 1 Types of Testing 2 2 6 2.1 Scaffolding................. 7 2.1.1 Drivers............... 7 2.1.2 Stubs................ 13 3 Integration Testing 17 1 1 Types of Testing

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table

More information

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

Unit Testing. Steven Zeil. July 22, Types of Testing 2. 2 Unit Testing Scaffolding Drivers Stubs... Steven Zeil July 22, 2013 Contents 1 Types of Testing 2 2 Unit Testing 4 2.1 Scaffolding............ 4 2.1.1 Drivers.......... 4 2.1.2 Stubs........... 9 3 Integration Testing 12 1 1 Types of Testing Testing

More information