Classes: A Deeper Look, Part 1

Size: px
Start display at page:

Download "Classes: A Deeper Look, Part 1"

Transcription

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 in a source-code file. To understand class scope and accessing class members via the name of an object, a reference to an object or a pointer to an object. To define constructors with default arguments. How destructors are used to perform termination housekeeping on an object before it is destroyed. When constructors and destructors are called. My object all sublime I shall achieve in time. W. S. Gilbert Is it a world to hide virtues in? William Shakespeare Don t be consistent, but be simply true. Oliver Wendell Holmes, Jr. This above all: to thine own self be true. William Shakespeare The logic errors that may occur when a public member function of a class returns a reference to private data. To assign the data members of one object to those of another object by default memberwise assignment.

2 Solutions 481 Self-Review Exercises 9.1 Fill in the blanks in each of the following: a) Class members are accessed via the operator in conjunction with the name of an object (or reference to an object) of the class or via the operator in conjunction with a pointer to an object of the class. ANS: dot (.), arrow (->). b) Class members specified as are accessible only to member functions of the class and friends of the class. ANS: private. c) Class members specified as are accessible anywhere an object of the class is in scope. ANS: public. d) can be used to assign an object of a class to another object of the same class. ANS: Default memberwise assignment (performed by the assignment operator). 9.2 Find the error(s) in each of the following and explain how to correct it (them): a) Assume the following prototype is declared in class Time: Solutions void ~Time( int ); ANS: Error: Destructors are not allowed to return values (or even specify a return type) or take arguments. Correction: Remove the return type void and the parameter int from the declaration. b) The following is a partial definition of class Time: class Time { public: // function prototypes private: int hour = 0; int minute = 0; int second = 0; }; // end class Time ANS: Error: Members cannot be explicitly initialized in the class definition. Correction: Remove the explicit initialization from the class definition and initialize the data members in a constructor. c) Assume the following prototype is declared in class Employee: int Employee( const char *, const char * ); ANS: Error: Constructors are not allowed to return values. Correction: Remove the return type int from the declaration. 9.3 What is the purpose of the scope resolution operator? ANS: The scope resolution operator is used to specify the class to which a function belongs. It also resolves the ambiguity caused by multiple classes having member functions of the same name. It also associates a member function in a.cpp file with a class definition in a.h file.

3 482 Chapter 9 Classes: A Deeper Look, Part (Enhancing Class Time) Provide a constructor that is capable of using the current time from the time() function declared in the C++ Standard Library header <ctime> to initialize an object of the Time class. ANS: [Note: We provide two solutions. The first one only uses function time. The second one uses several other data member and functions in <ctime> header.] 1 // Exercise 9.4 Solution: Time.h 2 #ifndef TIME_H 3 #define TIME_H 4 5 class Time 6 { 7 public: 8 Time(); // constructor 9 void settime( int, int, int ); // set hour, minute and second 10 void printuniversal(); // print time in universal-time format 11 void printstandard(); // print time in standard-time format 12 private: 13 int hour; // 0-23 (24-hour clock format) 14 int minute; // int second; // bool isleapyear( int ); // check if input is a leap year 17 }; // end class Time #endif 1 // Exercise 9.4 Solution: Time.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> 4 using std::cout; 5 6 #include <iomanip> 7 using std::setfill; 8 using std::setw; 9 10 #include <ctime> 11 using std::time; #include "Time.h" // include definition of class Time from Time.h Time::Time() 16 { 17 const int CURRENT_YEAR = 2004; 18 const int START_YEAR = 1970; 19 const int HOURS_IN_A_DAY = 24; 20 const int MINUTES_IN_AN_HOUR = 60; 21 const int SECONDS_IN_A_MINUTE = 60; 22 const int DAYS_IN_A_YEAR = 365; 23 const int DAYS_IN_A_LEAPYEAR = 366; 24 const int TIMEZONE_DIFFERENCE = 5; 25 int leapyear = 0; 26 int days; 27

4 Solutions // calculate leap year 29 for ( int y = START_YEAR; y <= CURRENT_YEAR; y++ ) 30 { 31 if ( isleapyear( y ) ) 32 leapyear++; 33 } // end for int daytimeinseconds = time( 0 ) - HOURS_IN_A_DAY * 36 MINUTES_IN_AN_HOUR * SECONDS_IN_A_MINUTE * ( 37 DAYS_IN_A_YEAR * ( CURRENT_YEAR - START_YEAR ) + leapyear ); // calculate current second, minute and hour 40 for ( int s = 0; s < SECONDS_IN_A_MINUTE; s++ ) 41 { 42 for ( int m = 0; m < MINUTES_IN_AN_HOUR; m++ ) 43 { 44 for ( int h = 0; h <= HOURS_IN_A_DAY; h++ ) 45 { 46 if ( isleapyear( CURRENT_YEAR ) ) 47 days = DAYS_IN_A_LEAPYEAR; 48 else 49 days = DAYS_IN_A_YEAR; for ( int d = 0; d <= days; d++ ) 52 { 53 if ( s + m * SECONDS_IN_A_MINUTE + 54 h * MINUTES_IN_AN_HOUR * SECONDS_IN_A_MINUTE + 55 d * HOURS_IN_A_DAY * MINUTES_IN_AN_HOUR * 56 SECONDS_IN_A_MINUTE == daytimeinseconds ) 57 { 58 settime( h-timezone_difference, m, s ); 59 } // end if 60 } // end for 61 } // end for 62 } // end for 63 } // end for 64 } // end Time constructor // set new Time value using universal time; ensure that 67 // the data remains consistent by setting invalid values to zero 68 void Time::setTime( int h, int m, int s ) 69 { 70 hour = ( h >= 0 && h < 24 )? h : 0; // validate hour 71 minute = ( m >= 0 && m < 60 )? m : 0; // validate minute 72 second = ( s >= 0 && s < 60 )? s : 0; // validate second 73 } // end function settime // print Time in universal-time format (HH:MM:SS) 76 void Time::printUniversal() 77 { 78 cout << setfill( '0' ) << setw( 2 ) << hour << ":" 79 << setw( 2 ) << minute << ":" << setw( 2 ) << second; 80 } // end function printuniversal // print Time in standard-time format (HH:MM:SS AM or PM)

5 484 Chapter 9 Classes: A Deeper Look, Part 1 83 void Time::printStandard() 84 { 85 cout << ( ( hour == 0 hour == 12 )? 12 : hour % 12 ) << ":" 86 << setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 ) 87 << second << ( hour < 12? " AM" : " PM" ); 88 } // end function printstandard // check if a year is a leap year 91 bool Time::isLeapYear( int y ) 92 { 93 if ( ( y % 400 == 0 ) ( ( y % 4 == 0 ) && ( y % 100!= 0 ) ) ) 94 return true; 95 else 96 return false; 97 } // end function isleapyear 1 // Exercise 9.4 Solution: Ex09_04.cpp 2 #include <iostream> 3 using std::cout; 4 using std::endl; 5 6 #include "Time.h" 7 8 int main() 9 { 10 Time t; // create Time object // display current time 13 cout << "The universal time is "; 14 t.printuniversal(); 15 cout << "\nthe standard time is "; 16 t.printstandard(); 17 cout << endl; 18 return 0; 19 } // end main The universal time is 14:54:06 The standard time is 2:54:06 PM 1 // Exercise 9.4 Solution: Time.h 2 #ifndef TIME_H 3 #define TIME_H 4 5 class Time 6 { 7 public: 8 Time(); // constructor 9 void settime( int, int, int ); // set hour, minute and second 10 void printuniversal(); // print time in universal-time format

6 Solutions void printstandard(); // print time in standard-time format 12 private: 13 int hour; // 0-23 (24-hour clock format) 14 int minute; // int second; // }; // end class Time #endif 1 // Exercise 9.4 Solution: Time.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> 4 using std::cout; 5 6 #include <iomanip> 7 using std::setfill; 8 using std::setw; 9 10 #include <ctime> 11 using std::localtime; 12 using std::time; 13 using std::time_t; #include "Time.h" // include definition of class Time from Time.h Time::Time() 18 { 19 const time_t currenttime = time( 0 ); 20 const tm *localtime = localtime( &currenttime ); 21 settime( localtime->tm_hour, localtime->tm_min, localtime->tm_sec ); 22 } // end Time constructor // set new Time value using universal time; ensure that 25 // the data remains consistent by setting invalid values to zero 26 void Time::setTime( int h, int m, int s ) 27 { 28 hour = ( h >= 0 && h < 24 )? h : 0; // validate hour 29 minute = ( m >= 0 && m < 60 )? m : 0; // validate minute 30 second = ( s >= 0 && s < 60 )? s : 0; // validate second 31 } // end function settime // print Time in universal-time format (HH:MM:SS) 34 void Time::printUniversal() 35 { 36 cout << setfill( '0' ) << setw( 2 ) << hour << ":" 37 << setw( 2 ) << minute << ":" << setw( 2 ) << second; 38 } // end function printuniversal // print Time in standard-time format (HH:MM:SS AM or PM) 41 void Time::printStandard() 42 { 43 cout << ( ( hour == 0 hour == 12 )? 12 : hour % 12 ) << ":" 44 << setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 ) 45 << second << ( hour < 12? " AM" : " PM" );

7 486 Chapter 9 Classes: A Deeper Look, Part 1 46 } // end function printstandard 9.5 (Complex Class) Create a class called Complex for performing arithmetic with complex numbers. Write a program to test your class. Complex numbers have the form where i is 1 realpart + imaginarypart * i Use double variables to represent the private data of the class. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should contain default values in case no initializers are provided. Provide public member functions that perform the following tasks: a) Adding two Complex numbers: The real parts are added together and the imaginary parts are added together. b) Subtracting two Complex numbers: The real part of the right operand is subtracted from the real part of the left operand, and the imaginary part of the right operand is subtracted from the imaginary part of the left operand. c) Printing Complex numbers in the form (a, b), where a is the real part and b is the imaginary part. ANS: 1 // Exercise 9.5 Solution: Complex.h 2 #ifndef COMPLEX_H 3 #define COMPLEX_H 4 5 class Complex 6 { 7 public: 8 Complex( double = 0.0, double = 0.0 ); // default constructor 9 Complex add( const Complex & ); // function add 10 Complex subtract( const Complex & ); // function subtract 11 void printcomplex(); // print complex number format 12 void setcomplexnumber( double, double ); // set complex number 13 private: 14 double realpart; 15 double imaginarypart; 16 }; // end class Complex #endif 1 // Exercise 9.5 Solution: Complex.cpp 2 // Member-function definitions for class Complex. 3 #include <iostream> 4 using std::cout; 5 6 #include "Complex.h" 7 8 Complex::Complex( double real, double imaginary ) 9 {

8 Solutions setcomplexnumber( real, imaginary ); 11 } // end Complex constructor Complex Complex::add( const Complex &right ) 14 { 15 return Complex( 16 realpart + right.realpart, imaginarypart + right.imaginarypart ); 17 } // end function add Complex Complex::subtract( const Complex &right ) 20 { 21 return Complex( 22 realpart - right.realpart, imaginarypart - right.imaginarypart ); 23 } // end function subtract void Complex::printComplex() 26 { 27 cout << '(' << realpart << ", " << imaginarypart << ')'; 28 } // end function printcomplex void Complex::setComplexNumber( double rp, double ip ) 31 { 32 realpart = rp; 33 imaginarypart = ip; 34 } // end function setcomplexnumber 1 // Exercise 9.5 Solution: Ex09_05.cpp 2 #include <iostream> 3 using std::cout; 4 using std::endl; 5 6 #include "Complex.h" 7 8 int main() 9 { 10 Complex a( 1, 7 ), b( 9, 2 ), c; // create three Complex objects a.printcomplex(); // output object a 13 cout << " + "; 14 b.printcomplex(); // output object b 15 cout << " = "; 16 c = a.add( b ); // invoke add function and assign to object c 17 c.printcomplex(); // output object c cout << '\n'; 20 a.setcomplexnumber( 10, 1 ); // reset realpart and 21 b.setcomplexnumber( 11, 5 ); // and imaginarypart 22 a.printcomplex(); // output object a 23 cout << " - "; 24 b.printcomplex(); // output object b 25 cout << " = "; 26 c = a.subtract( b ); // invoke add function and assign to object c 27 c.printcomplex(); // output object c 28 cout << endl;

9 488 Chapter 9 Classes: A Deeper Look, Part 1 29 return 0; 30 } // end main (1, 7) + (9, 2) = (10, 9) (10, 1) - (11, 5) = (-1, -4) 9.6 (Rational Class) Create a class called Rational for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private data of the class the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should contain default values in case no initializers are provided and should store the fraction in reduced form. For example, the fraction would be stored in the object as 1 in the numerator and 2 in the denominator. Provide public member functions that perform each of the following tasks: a) Adding two Rational numbers. The result should be stored in reduced form. b) Subtracting two Rational numbers. The result should be stored in reduced form. c) Multiplying two Rational numbers. The result should be stored in reduced form. d) Dividing two Rational numbers. The result should be stored in reduced form. e) Printing Rational numbers in the form a/b, where a is the numerator and b is the denominator. f) Printing Rational numbers in floating-point format. ANS: 1 // Exercise 9.6 Solution: Rational.h 2 #ifndef RATIONAL_H 3 #define RATIONAL_H 4 5 class Rational 6 { 7 public: 8 Rational( int = 0, int = 1 ); // default constructor 9 Rational addition( const Rational & ); // function addition 10 Rational subtraction( const Rational & ); // function subtraction 11 Rational multiplication( const Rational & ); // function multi. 12 Rational division( const Rational & ); // function division 13 void printrational (); // print rational format 14 void printrationalasdouble(); // print rational as double format 15 private: 16 int numerator; // integer numerator 17 int denominator; // integer denominator 18 void reduction(); // utility function 19 }; // end class Rational #endif 1 // Exercise 9.6 Solution: Rational.cpp 2 // Member-function definitions for class Rational. 3 #include <iostream>

10 4 using std::cout; 5 6 #include "Rational.h" // include definition of class Rational 7 8 Rational::Rational( int n, int d ) 9 { 10 numerator = n; // sets numerator 11 denominator = d; // sets denominator 12 reduction(); // store the fraction in reduced form 13 } // end Rational constructor Rational Rational::addition( const Rational &a ) 16 { 17 Rational t; // creates Rational object t.numerator = a.numerator * denominator; 20 t.numerator += a.denominator * numerator; 21 t.denominator = a.denominator * denominator; 22 t.reduction(); // store the fraction in reduced form 23 return t; 24 } // end function addition Rational Rational::subtraction( const Rational &s ) 27 { 28 Rational t; // creates Rational object t.numerator = s.denominator * numerator; 31 t.numerator -= denominator * s.numerator; 32 t.denominator = s.denominator * denominator; 33 t.reduction(); // store the fraction in reduced form 34 return t; 35 } // end function subtraction Rational Rational::multiplication( const Rational &m ) 38 { 39 Rational t; // creates Rational object t.numerator = m.numerator * numerator; 42 t.denominator = m.denominator * denominator; 43 t.reduction(); // store the fraction in reduced form 44 return t; 45 } // end function multiplication Rational Rational::division( const Rational &v ) 48 { 49 Rational t; // creates Rational object t.numerator = v.denominator * numerator; 52 t.denominator = denominator * v.numerator; 53 t.reduction(); // store the fraction in reduced form 54 return t; 55 } // end function division void Rational::printRational () 58 { Solutions 489

11 490 Chapter 9 Classes: A Deeper Look, Part 1 59 if ( denominator == 0 ) // validates denominator 60 cout << "\ndivide BY ZERO ERROR!!!" << '\n'; 61 else if ( numerator == 0 ) // validates numerator 62 cout << 0; 63 else 64 cout << numerator << '/' << denominator; 65 } // end function printrational void Rational::printRationalAsDouble() 68 { 69 cout << static_cast< double >( numerator ) / denominator; 70 } // end function printrationalasdouble void Rational::reduction() 73 { 74 int largest; 75 largest = numerator > denominator? numerator : denominator; int gcd = 0; // greatest common divisor for ( int loop = 2; loop <= largest; loop++ ) if ( numerator % loop == 0 && denominator % loop == 0 ) 82 gcd = loop; if (gcd!= 0) 85 { 86 numerator /= gcd; 87 denominator /= gcd; 88 } // end if 89 } // end function reduction 1 // Exercise 9.6 Solution: Ex09_06.cpp 2 #include <iostream> 3 using std::cout; 4 using std::endl; 5 6 #include "Rational.h" // include definition of class Rational 7 8 int main() 9 { 10 Rational c( 2, 6 ), d( 7, 8 ), x; // creates three rational objects c.printrational(); // prints rational object c 13 cout << " + "; 14 d.printrational(); // prints rational object d 15 x = c.addition( d ); // adds object c and d; sets the value to x cout << " = "; 18 x.printrational(); // prints rational object x 19 cout << '\n'; 20 x.printrational(); // prints rational object x 21 cout << " = "; 22 x.printrationalasdouble(); // prints rational object x as double

12 Solutions cout << "\n\n"; c.printrational(); // prints rational object c 26 cout << " - "; 27 d.printrational(); // prints rational object d 28 x = c.subtraction( d ); // subtracts object c and d cout << " = "; 31 x.printrational(); // prints rational object x 32 cout << '\n'; 33 x.printrational(); // prints rational object x 34 cout << " = "; 35 x.printrationalasdouble(); // prints rational object x as double 36 cout << "\n\n"; c.printrational(); // prints rational object c 39 cout << " x "; 40 d.printrational(); // prints rational object d 41 x = c.multiplication( d ); // multiplies object c and d cout << " = "; 44 x.printrational(); // prints rational object x 45 cout << '\n'; 46 x.printrational(); // prints rational object x 47 cout << " = "; 48 x.printrationalasdouble(); // prints rational object x as double 49 cout << "\n\n"; c.printrational(); // prints rational object c 52 cout << " / "; 53 d.printrational(); // prints rational object d 54 x = c.division( d ); // divides object c and d cout << " = "; 57 x.printrational(); // prints rational object x 58 cout << '\n'; 59 x.printrational(); // prints rational object x 60 cout << " = "; 61 x.printrationalasdouble(); // prints rational object x as double 62 cout << endl; 63 return 0; 64 } // end main 1/3 + 7/8 = 29/24 29/24 = /3-7/8 = -13/24-13/24 = /3 x 7/8 = 7/24 7/24 = /3 / 7/8 = 8/21 8/21 =

13 492 Chapter 9 Classes: A Deeper Look, Part (Enhancing Class Time) Modify the Time class of Figs to include a tick member function that increments the time stored in a Time object by one second. The Time object should always remain in a consistent state. Write a program that tests the tick member function in a loop that prints the time in standard format during each iteration of the loop to illustrate that the tick member function works correctly. Be sure to test the following cases: a) Incrementing into the next minute. b) Incrementing into the next hour. c) Incrementing into the next day (i.e., 11:59:59 PM to 12:00:00 AM). ANS: 1 // Exercise 9.7 Solution: Time.h 2 #ifndef TIME_H 3 #define TIME_H 4 5 class Time 6 { 7 public: 8 public: 9 Time( int = 0, int = 0, int = 0 ); // default constructor // set functions 12 void settime( int, int, int ); // set hour, minute, second 13 void sethour( int ); // set hour (after validation) 14 void setminute( int ); // set minute (after validation) 15 void setsecond( int ); // set second (after validation) // get functions 18 int gethour(); // return hour 19 int getminute(); // return minute 20 int getsecond(); // return second void tick(); // increment one second 23 void printuniversal(); // output time in universal-time format 24 void printstandard(); // output time in standard-time format 25 private: 26 int hour; // 0-23 (24-hour clock format) 27 int minute; // int second; // }; // end class Time #endif 1 // Exercise 9.7: Time.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> 4 using std::cout; 5 6 #include <iomanip> 7 using std::setfill; 8 using std::setw; 9 10 #include "Time.h" // include definition of class Time from Time.h

14 Solutions // Time constructor initializes each data member to zero; 13 // ensures that Time objects start in a consistent state 14 Time::Time( int hr, int min, int sec ) 15 { 16 settime( hr, min, sec ); // validate and set time 17 } // end Time constructor // set new Time value using universal time; ensure that 20 // the data remains consistent by setting invalid values to zero 21 void Time::setTime( int h, int m, int s ) 22 { 23 sethour( h ); // set private field hour 24 setminute( m ); // set private field minute 25 setsecond( s ); // set private field second 26 } // end function settime // set hour value 29 void Time::setHour( int h ) 30 { 31 hour = ( h >= 0 && h < 24 )? h : 0; // validate hour 32 } // end function sethour // set minute value 35 void Time::setMinute( int m ) 36 { 37 minute = ( m >= 0 && m < 60 )? m : 0; // validate minute 38 } // end function setminute // set second value 41 void Time::setSecond( int s ) 42 { 43 second = ( s >= 0 && s < 60 )? s : 0; // validate second 44 } // end function setsecond // return hour value 47 int Time::getHour() 48 { 49 return hour; 50 } // end function gethour // return minute value 53 int Time::getMinute() 54 { 55 return minute; 56 } // end function getminute // return second value 59 int Time::getSecond() 60 { 61 return second; 62 } // end function getsecond // increment one second 65 void Time::tick()

15 494 Chapter 9 Classes: A Deeper Look, Part 1 66 { 67 setsecond( getsecond() + 1 ); // increment second by if ( getsecond() == 0 ) 70 { 71 setminute( getminute() + 1 ); // increment minute by if ( getminute() == 0 ) 74 sethour( gethour() + 1 ); // increment hour by 1 75 } // end if 76 } // end function tick // print Time in universal-time format (HH:MM:SS) 79 void Time::printUniversal() 80 { 81 cout << setfill( '0' ) << setw( 2 ) << gethour() << ":" 82 << setw( 2 ) << getminute() << ":" << setw( 2 ) << getsecond(); 83 } // end function printuniversal // print Time in standard-time format (HH:MM:SS AM or PM) 86 void Time::printStandard() 87 { 88 cout << ( ( gethour() == 0 gethour() == 12 )? 12 : gethour() % 12 ) 89 << ":" << setfill( '0' ) << setw( 2 ) << getminute() 90 << ":" << setw( 2 ) << getsecond() << ( hour < 12? " AM" : " PM" ); 91 } // end function printstandard 1 // Exercise 9.7: Ex09_07.cpp 2 #include <iostream> 3 using std::cout; 4 using std::endl; 5 6 #include "Time.h" // include definition of class Time 7 8 const int MAX_TICKS = 30; 9 10 int main() 11 { 12 Time t; // instantiate object t of class Time t.settime( 23, 59, 57 ); // set time // output Time object t's values 17 for ( int ticks = 1; ticks < MAX_TICKS; ++ticks ) 18 { 19 t.printstandard(); // invokes function printstandard 20 cout << endl; 21 t.tick(); // invokes function tick 22 } // end for return 0; 25 } // end main

16 Solutions :59:57 PM 11:59:58 PM 11:59:59 PM 12:00:00 AM 12:00:01 AM (Enhancing Class Date) Modify the Date class of Fig to perform error checking on the initializer values for data members month, day and year. Also, provide a member function nextday to increment the day by one. The Date object should always remain in a consistent state. Write a program that tests function nextday in a loop that prints the date during each iteration to illustrate that nextday works correctly. Be sure to test the following cases: a) Incrementing into the next month. b) Incrementing into the next year. ANS: 1 // Exercise 9.8 Solution: Date.h 2 #ifndef DATE_H 3 #define DATE_H 4 5 class Date 6 { 7 public: 8 Date( int = 1, int = 1, int = 1900 ); // default constructor 9 void print(); // print function 10 void setdate( int, int, int ); // set month, day, year 11 void setmonth( int ); // set month 12 void setday( int ); // set day 13 void setyear( int ); // set year 14 int getmonth(); // get month 15 int getday(); // get day 16 int getyear(); // get year 17 void nextday(); // next day 18 private: 19 int month; // int day; // 1-31 (except February(leap year), April, June, Sept, Nov) 21 int year; // bool leapyear(); // leap year 23 int monthdays(); // days in month 24 }; // end class Date #endif 1 // Exercise 9.8 Solution: Date.cpp 2 // Member-function definitions for class Date. 3 #include <iostream> 4 using std::cout; 5 6 #include "Date.h" // include definition of class Date

17 496 Chapter 9 Classes: A Deeper Look, Part Date::Date( int m, int d, int y ) 9 { 10 setdate( m, d, y ); // sets date 11 } // end Date constructor void Date::setDate( int mo, int dy, int yr ) 14 { 15 setmonth( mo ); // invokes function setmonth 16 setday( dy ); // invokes function setday 17 setyear( yr ); // invokes function setyear 18 } // end function setdate void Date::setDay( int d ) 21 { 22 if ( month == 2 && leapyear() ) 23 day = ( d <= 29 && d >= 1 )? d : 1; 24 else 25 day = ( d <= monthdays() && d >= 1 )? d : 1; 26 } // end function setday void Date::setMonth( int m ) 29 { 30 month = m <= 12 && m >= 1? m : 1; // sets month 31 } // end function setmonth void Date::setYear( int y ) 34 { 35 year = y >= 1900? y : 1900; // sets year 36 } // end function setyear int Date::getDay() 39 { 40 return day; 41 } // end function getday int Date::getMonth() 44 { 45 return month; 46 } // end function getmonth int Date::getYear() 49 { 50 return year; 51 } // end function getyear void Date::print() 54 { 55 cout << month << '-' << day << '-' << year << '\n'; // outputs date 56 } // end function print void Date::nextDay() 59 { 60 setday( day + 1 ); // increments day by 1 61

18 Solutions if ( day == 1 ) 63 { 64 setmonth( month + 1 ); // increments month by if ( month == 1 ) 67 setyear( year + 1 ); // increments year by 1 68 } // end if statement 69 } // end function nextday bool Date::leapYear() 72 { 73 if ( year % 400 == 0 ( year % 4 == 0 && year % 100!= 0 ) ) 74 return true; // is a leap year 75 else 76 return false; // is not a leap year 77 } // end function leapyear int Date::monthDays() 80 { 81 const int days[ 12 ] = 82 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return month == 2 && leapyear()? 29 : days[ month - 1 ]; 85 } // end function monthdays 1 // Exercise 9.8 Solution: Ex09_08.cpp 2 #include <iostream> 3 using std::cout; 4 using std::endl; 5 6 #include "Date.h" // include definitions of class Date 7 8 int main() 9 { 10 const int MAXDAYS = 16; 11 Date d( 12, 24, 2004 ); // instantiate object d of class Date // output Date object d's value 14 for ( int loop = 1; loop <= MAXDAYS; ++loop ) 15 { 16 d.print(); // invokes function print 17 d.nextday(); // invokes function next day 18 } // end for cout << endl; 21 return 0; 22 } // end main

19 498 Chapter 9 Classes: A Deeper Look, Part (Combining Class Time and Class Date) Combine the modified Time class of Exercise 9.7 and the modified Date class of Exercise 9.8 into one class called DateAndTime. (In Chapter 12, we will discuss inheritance, which will enable us to accomplish this task quickly without modifying the existing class definitions.) Modify the tick function to call the nextday function if the time increments into the next day. Modify functions printstandard and printuniversal to output the date and time. Write a program to test the new class DateAndTime. Specifically, test incrementing the time into the next day. ANS: 1 // Exercise 9.9 Solution: DateAndTime.h 2 #ifndef DATEANDTIME_H 3 #define DATEANDTIME_H 4 5 class DateAndTime 6 { 7 public: 8 DateAndTime( int = 1, int = 1, int = 1900, 9 int = 0, int = 0, int = 0 ); // default constructor 10 void setdate( int, int, int ); // set month, day, year 11 void setmonth( int ); // set month 12 void setday( int ); // set day 13 void setyear( int ); // set year 14 void nextday(); // next day 15 void settime( int, int, int ); // set hour, minute, second 16 void sethour( int ); // set hour 17 void setminute( int ); // set minute 18 void setsecond( int ); // set second 19 void tick(); // tick function 20 int getmonth(); // get month 21 int getday(); // get day 22 int getyear(); // get year 23 int gethour(); // get hour 24 int getminute(); // get minute 25 int getsecond(); // get second 26 void printstandard(); // print standard time

20 Solutions void printuniversal(); // print universal time 28 private: 29 int month; // int day; // 1-31 (except February(leap year), April, June, Sept, Nov) 31 int year; // int hour; // 0-23 (24 hour clock format) 33 int minute; // int second; // bool leapyear(); // leap year 36 int monthdays(); // days in month 37 }; // end class DateAndTime #endif 1 // Exercise 9.9 Solution: DateAndTime.cpp 2 // Member function definitions for class DateAndTime. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 7 #include "DateAndTime.h" // include definition of class DateAndTime 8 9 DateAndTime::DateAndTime( 10 int m, int d, int y, int hr, int min, int sec ) 11 { 12 setdate( m, d, y ); // sets date 13 settime( hr, min, sec ); // sets time 14 } // end DateAndTime constructor void DateAndTime::setDate( int mo, int dy, int yr ) 17 { 18 setmonth( mo ); // invokes function setmonth 19 setday( dy ); // invokes function setday 20 setyear( yr ); // invokes function setyear 21 } // end function setdate void DateAndTime::setDay( int d ) 24 { 25 if ( month == 2 && leapyear() ) 26 day = ( d <= 29 && d >= 1 )? d : 1; 27 else 28 day = ( d <= monthdays() && d >= 1 )? d : 1; 29 } // end function setday void DateAndTime::setMonth( int m ) 32 { 33 month = m <= 12 && m >= 1? m : 1; // sets month 34 } // end function setmonth void DateAndTime::setYear( int y ) 37 { 38 year = y >= 1900? y : 1900; // sets year 39 } // end function setyear 40

21 500 Chapter 9 Classes: A Deeper Look, Part 1 41 void DateAndTime::nextDay() 42 { 43 setday( day + 1 ); // increments day by if ( day == 1 ) 46 { 47 setmonth( month + 1 ); // increments month by if ( month == 1 ) 50 setyear( year + 1 ); // increments year by 1 51 } // end if statement 52 } //end function nextday void DateAndTime::setTime( int hr, int min, int sec ) 55 { 56 sethour( hr ); // invokes function sethour 57 setminute( min ); // invokes function setminute 58 setsecond( sec ); // invokes function setsecond 59 } // end function settime void DateAndTime::setHour( int h ) 62 { 63 hour = ( h >= 0 && h < 24 )? h : 0; // sets hour 64 } // end function sethour void DateAndTime::setMinute( int m ) 67 { 68 minute = ( m >= 0 && m < 60 )? m : 0; // sets minute 69 } // end function setminute void DateAndTime::setSecond( int s ) 72 { 73 second = ( s >= 0 && s < 60 )? s : 0; // sets second 74 } // end function setsecond void DateAndTime::tick() 77 { 78 setsecond( second + 1 ); // increments second by if ( second == 0 ) 81 { 82 setminute( minute + 1 ); // increments minute by if ( minute == 0 ) 85 { 86 sethour( hour + 1 ); // increments hour by if ( hour == 0 ) 89 nextday(); // increments day by 1 90 } // end if 91 } // end if 92 } // end function tick int DateAndTime::getDay() 95 {

22 Solutions return day; 97 } // end function getday int DateAndTime::getMonth() 100 { 101 return month; 102 } // end function getmonth int DateAndTime::getYear() 105 { 106 return year; 107 } // end function getyear int DateAndTime::getHour() 110 { 111 return hour; 112 } // end function gethour int DateAndTime::getMinute() 115 { 116 return minute; 117 } // end function getminute int DateAndTime::getSecond() 120 { 121 return second; 122 } // end function getsecond void DateAndTime::printStandard() 125 { 126 cout << ( ( hour % 12 == 0 )? 12 : hour % 12 ) << ':' 127 << ( minute < 10? "0" : "" ) << minute << ':' 128 << ( second < 10? "0" : "" ) << second 129 << ( hour < 12? " AM " : " PM " ) 130 << month << '-' << day << '-' << year << endl; 131 } // end function printstandard void DateAndTime::printUniversal() 134 { 135 cout << ( hour < 10? "0" : "" ) << hour << ':' 136 << ( minute < 10? "0" : "" ) << minute << ':' 137 << ( second < 10? "0" : "" ) << second << " " 138 << month << '-' << day << '-' << year << endl; 139 } // end function printuniversal bool DateAndTime::leapYear() 142 { 143 if ( year % 400 == 0 ( year % 4 == 0 && year % 100!= 0 ) ) 144 return true; // is a leap year 145 else 146 return false; // is not a leap year 147 } // end function leapyear int DateAndTime::monthDays() 150 {

23 502 Chapter 9 Classes: A Deeper Look, Part const int days[ 12 ] = { , 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return ( month == 2 && leapyear() )? 29 : days[ ( month - 1 ) ]; 155 } // end function monthdays 1 // Exercise 9.9 Solution: Ex09_09.cpp 2 #include <iostream> 3 using std::cout; 4 using std::endl; 5 6 #include "DateAndTime.h" // include definitions of class DateAndTime 7 8 int main() 9 { 10 const int MAXTICKS = 30; 11 DateAndTime d( 12, 31, 2004, 23, 59, 57 ); // instantiates object d 12 // of class DateAndTime for ( int ticks = 1; ticks <= MAXTICKS; ticks++ ) 15 { 16 cout << "Universal time: "; 17 d.printuniversal(); // invokes function printuniversal 18 cout << "Standard time: "; 19 d.printstandard(); // invokes function printstandard 20 d.tick(); // invokes function tick 21 } // end for cout << endl; 24 return 0; 25 } // end main Universal time: 23:59: Standard time: 11:59:57 PM Universal time: 23:59: Standard time: 11:59:58 PM Universal time: 23:59: Standard time: 11:59:59 PM Universal time: 00:00: Standard time: 12:00:00 AM Universal time: 00:00: Standard time: 12:00:01 AM (Returning Error Indicators from Class Time s set Functions) Modify the set functions in the Time class of Figs to return appropriate error values if an attempt is made to set a data mem-

24 Solutions 503 ber of an object of class Time to an invalid value. Write a program that tests your new version of class Time. Display error messages when set functions return error values. ANS: 1 // Exercise 9.10 Solution: Time.h 2 #ifndef TIME_H 3 #define TIME_H 4 5 class Time 6 { 7 public: 8 Time( int = 0, int = 0, int = 0 ); // default constructor 9 bool settime( int, int, int ); // set hour, minute, second 10 bool sethour( int ); // set hour 11 bool setminute( int ); // set minute 12 bool setsecond( int ); // set second 13 int gethour(); // get hour 14 int getminute(); // get minute 15 int getsecond(); // get second 16 void printuniversal(); // print universal time 17 void printstandard(); // print standard time 18 private: 19 int hour; // int minute; // int second; // }; // end class Time #endif 1 // Exercise 9.10 Solution: Time.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> 4 using std::cout; 5 6 #include "Time.h" // include definition of class Time 7 8 Time::Time( int hr, int min, int sec ) 9 { 10 settime( hr, min, sec ); 11 } // end Time constructor bool Time::setTime( int h, int m, int s ) 14 { 15 bool hourvalid = sethour( h ); // invokes function sethour 16 bool minutevalid = setminute( m ); // invokes function setminute 17 bool secondvalid = setsecond( s ); // invokes function setsecond 18 return hourvalid && minutevalid && secondvalid; 19 } // end function settime bool Time::setHour( int hr ) 22 { 23 if ( hr >= 0 && hr < 24 ) 24 {

25 504 Chapter 9 Classes: A Deeper Look, Part 1 25 hour = hr; 26 return true; // hour is valid 27 } // end if 28 else 29 { 30 hour = 0; 31 return false; // hour is invalid 32 } // end else 33 } // end function sethour bool Time::setMinute( int min ) 36 { 37 if ( min >= 0 && min < 60 ) 38 { 39 minute = min; 40 return true; // minute is valid 41 } // end if 42 else 43 { 44 minute = 0; 45 return false; // minute is invalid 46 } // end else 47 } // end function setminute bool Time::setSecond( int sec ) 50 { 51 if ( sec >= 0 && sec < 60 ) 52 { 53 second = sec; 54 return true; // second is valid 55 } // end if 56 else 57 { 58 second = 0; 59 return false; // second is invalid 60 } // end else 61 } // end function setsecond // return hour value 64 int Time::getHour() 65 { 66 return hour; 67 } // end function gethour // return minute value 70 int Time::getMinute() 71 { 72 return minute; 73 } // end function getminute // return second value 76 int Time::getSecond() 77 { 78 return second; 79 } // end function getsecond

26 Solutions void Time::printUniversal() 82 { 83 cout << ( hour < 10? "0" : "" ) << hour << ':' 84 << ( minute < 10? "0" : "" ) << minute << ':' 85 << ( second < 10? "0" : "" ) << second; 86 } // end function printuniversal void Time::printStandard() 89 { 90 cout << ( ( hour % 12 == 0 )? 12 : hour % 12 ) << ':' 91 << ( minute < 10? "0": "" ) << minute << ':' 92 << ( second < 10? "0": "" ) << second 93 << ( hour < 12? " AM" : " PM" ); 94 } // end function printstandard 1 // Exercise 9.10 Solution: Ex09_10.cpp 2 #include <iostream> 3 using std::cin; 4 using std::cout; 5 using std::endl; 6 7 #include "Time.h" // include definition of class Time 8 9 int main() 10 { 11 Time time; // the Time object // all t1 object's times are valid 15 if (!t1.getinvalidtime() ) 16 cout << "Error: invalid time setting(s) attempted." << '\n' 17 << "Invalid setting(s) changed to zero." << '\n'; t1.printstandard(); // invokes function print standard // object t2 has invalid time settings 22 if (!t2.getinvalidtime() ) 23 cout << "\nerror: invalid time setting(s) attempted.\n" 24 << "Invalid setting(s) changed to zero.\n"; t2.printuniversal(); // invokes function print universal 27 cout << endl; return 0; 30 } // end main 1 // Exercise 9.10 Solution: Ex09_10.cpp 2 #include <iostream> 3 using std::cin; 4 using std::cout; 5 using std::endl; 6

27 506 Chapter 9 Classes: A Deeper Look, Part 1 7 #include "Time.h" // include definition of class Time 8 9 int getmenuchoice(); // prototype int main() 12 { 13 Time time; // the Time object 14 int choice = getmenuchoice(); 15 int hours; 16 int minutes; 17 int seconds; while ( choice!= 4 ) 20 { 21 switch ( choice ) 22 { 23 case 1: // set hour 24 cout << "Enter Hours: "; 25 cin >> hours; if (!time.sethour( hours ) ) 28 cout << "Invalid hours." << endl; 29 break; 30 case 2: // set minute 31 cout << "Enter Minutes: "; 32 cin >> minutes; if (!time.setminute( minutes ) ) 35 cout << "Invalid minutes." << endl; 36 break; 37 case 3: // set seconds 38 cout << "Enter Seconds: "; 39 cin >> seconds; if (!time.setsecond( seconds ) ) 42 cout << "Invalid seconds." << endl; 43 break; 44 } // end switch cout << "Hour: " << time.gethour() << " Minute: " 47 << time.getminute() << " Second: " << time.getsecond() << endl; 48 cout << "Universal time: "; 49 time.printuniversal(); 50 cout << " Standard time: "; 51 time.printstandard(); 52 cout << endl; choice = getmenuchoice(); 55 } // end while 56 } // end main // prints a menu and returns a value corresponding to the menu choice 59 int getmenuchoice() 60 { 61 int choice;

28 Solutions cout << "1. Set Hour\n2. Set Minute\n3. Set Second\n" 64 << "4. Exit\nChoice: " << endl; 65 cin >> choice; 66 return choice; 67 } // end function getmenuchoice 1. Set Hour 2. Set Minute 3. Set Second 4. Exit Choice: 1 Enter Hours: 17 Hour: 17 Minute: 0 Second: 0 Universal time: 17:00:00 Standard time: 5:00:00 PM 1. Set Hour 2. Set Minute 3. Set Second 4. Exit Choice: 2 Enter Minutes: 65 Invalid minutes. Hour: 17 Minute: 0 Second: 0 Universal time: 17:00:00 Standard time: 5:00:00 PM 1. Set Hour 2. Set Minute 3. Set Second 4. Exit Choice: 3 Enter Seconds: 23 Hour: 17 Minute: 0 Second: 23 Universal time: 17:00:23 Standard time: 5:00:23 PM 1. Set Hour 2. Set Minute 3. Set Second 4. Exit Choice: (Rectangle Class) Create a class Rectangle with attributes length and width, each of which defaults to 1. Provide member functions that calculate the perimeter and the area of the rectangle. Also, provide set and get functions for the length and width attributes. The set functions should verify that length and width are each floating-point numbers larger than 0.0 and less than ANS: 1 // Exercise 9.11 Solution: Rectangle.h 2 #ifndef RECTANGLE_H 3 #define RECTANGLE_H 4 5 class Rectangle 6 {

29 508 Chapter 9 Classes: A Deeper Look, Part 1 7 public: 8 Rectangle( double = 1.0, double = 1.0 ); // default constructor 9 void setwidth( double w ); // set width 10 void setlength( double l ); // set length 11 double getwidth(); // get width 12 double getlength(); // get length 13 double perimeter(); // perimeter 14 double area(); // area 15 private: 16 double length; // 1.0 < length < double width; // 1.0 < width < }; // end class Rectangle #endif 1 // Exercise 9.11 Solution: Rectangle.cpp 2 // Member-function definitions for class Rectangle. 3 4 #include "Rectangle.h" // include definition of class Rectangle 5 6 Rectangle::Rectangle( double w, double l ) 7 { 8 setwidth(w); // invokes function setwidth 9 setlength(l); // invokes function setlength 10 } // end Rectangle constructor void Rectangle::setWidth( double w ) 13 { 14 width = w > 0 && w < 20.0? w : 1.0; // sets width 15 } // end function setwidth void Rectangle::setLength( double l ) 18 { 19 length = l > 0 && l < 20.0? l : 1.0; // sets length 20 } // end function setlength double Rectangle::getWidth() 23 { 24 return width; 25 } // end function getwidth double Rectangle::getLength() 28 { 29 return length; 30 } // end fucntion getlength double Rectangle::perimeter() 33 { 34 return 2 * ( width + length ); // returns perimeter 35 } // end function perimeter double Rectangle::area() 38 { 39 return width * length; // returns area

30 Solutions } // end function area 1 // Exercise 9.11 Solution: Ex09_11.cpp 2 #include <iostream> 3 using std::cout; 4 using std::endl; 5 using std::fixed; 6 7 #include <iomanip> 8 using std::setprecision; 9 10 #include "Rectangle.h" // include definition of class Rectangle int main() 13 { 14 Rectangle a, b( 4.0, 5.0 ), c( 67.0, ); cout << fixed; 17 cout << setprecision( 1 ); // output Rectangle a 20 cout << "a: length = " << a.getlength() << "; width = " 21 << a.getwidth() << "; perimeter = " << a.perimeter() 22 << "; area = " << a.area() << '\n'; // output Rectangle b 25 cout << "b: length = " << b.getlength() << "; width = " 26 << b.getwidth() << "; perimeter = " << b.perimeter() 27 << "; area = " << b.area() << '\n'; // output Rectangle c; bad values attempted 30 cout << "c: length = " << c.getlength() << "; width = " 31 << c.getwidth() << "; perimeter = " << c.perimeter() 32 << "; area = " << c.area() << endl; 33 return 0; 34 } // end main a: length = 1.0; width = 1.0; perimeter = 4.0; area = 1.0 b: length = 5.0; width = 4.0; perimeter = 18.0; area = 20.0 c: length = 1.0; width = 1.0; perimeter = 4.0; area = (Enhancing Class Rectangle) Create a more sophisticated Rectangle class than the one you created in Exercise This class stores only the Cartesian coordinates of the four corners of the rectangle. The constructor calls a set function that accepts four sets of coordinates and verifies that each of these is in the first quadrant with no single x- or y-coordinate larger than The set function also verifies that the supplied coordinates do, in fact, specify a rectangle. Provide member functions that calculate the length, width, perimeter and area. The length is the larger of the two dimensions. Include a predicate function square that determines whether the rectangle is a square. ANS: 1 // Exercise 9.12 Solution: Point.h

31 510 Chapter 9 Classes: A Deeper Look, Part 1 2 #ifndef POINT_H 3 #define POINT_H 4 5 class Point 6 { 7 public: 8 Point( double = 0.0, double = 0.0 ); // default constructor 9 10 // set and get functions 11 void setx( double ); 12 void sety( double ); 13 double getx(); 14 double gety(); 15 private: 16 double x; // 0.0 <= x <= double y; // 0.0 <= y <= }; // end class Point #endif 1 // Exercise 9.12 Solution: Point.cpp 2 // Member-function definitions for class Point. 3 4 #include "Point.h" // include definition of class Point 5 6 Point::Point( double xcoord, double ycoord ) 7 { 8 setx( xcoord ); // invoke function setx 9 sety( ycoord ); // invoke function sety 10 } // end Point constructor // set x coordinate 13 void Point::setX( double xcoord ) 14 { 15 x = ( xcoord >= 0.0 && xcoord <= 20.0 )? xcoord : 0.0; 16 } // end function setx // set y coordinate 19 void Point::setY( double ycoord ) 20 { 21 y = ( ycoord >= 0.0 && ycoord <= 20.0 )? ycoord : 0.0; 22 } // end function sety // return x coordinate 25 double Point::getX() 26 { 27 return x; 28 } // end function getx // return y coordinate 31 double Point::getY() 32 { 33 return y;

32 Solutions } // end function gety 1 // Exercise 9.12 Solution: Rectangle.h 2 #ifndef RECTANGLE_H 3 #define RECTANGLE_H 4 5 #include "Point.h" // include definition of class Point 6 7 class Rectangle 8 { 9 public: 10 // default constructor 11 Rectangle( Point = Point( 0.0, 1.0 ), Point = Point( 1.0, 1.0 ), 12 Point = Point( 1.0, 0.0 ), Point = Point( 0.0, 0.0 ) ); // sets x, y, x2, y2 coordinates 15 void setcoord( Point, Point, Point, Point ); 16 double length(); // length 17 double width(); // width 18 void perimeter(); // perimeter 19 void area(); // area 20 bool square(); // square 21 private: 22 Point point1; 23 Point point2; 24 Point point3; 25 Point point4; 26 }; // end class Rectangle #endif 1 // Exercise 9.12 Solution: Rectangle.cpp 2 // Member-function definitions for class Rectangle. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 7 #include <iomanip> 8 using std::fixed; 9 using std::setprecision; #include <cmath> 12 using std::fabs; #include "Rectangle.h" // include definition of class Rectangle Rectangle::Rectangle( Point a, Point b, Point c, Point d ) 17 { 18 setcoord( a, b, c, d ); // invokes function setcoord 19 } // end Rectangle constructor void Rectangle::setCoord( Point p1, Point p2, Point p3, Point p4 ) 22 {

33 512 Chapter 9 Classes: A Deeper Look, Part 1 23 // Arrangement of points 24 // p4...p3 25 //.. 26 //.. 27 // p1...p // verify that points form a rectangle 30 if ( ( p1.gety() == p2.gety() && p1.getx() == p4.getx() 31 && p2.getx() == p3.getx() && p3.gety() == p4.gety() ) ) 32 { 33 point1 = p1; 34 point2 = p2; 35 point3 = p3; 36 point4 = p4; 37 } // end if 38 else 39 { 40 cout << "Coordinates do not form a rectangle!\n" 41 << "Use default values.\n"; 42 point1 = Point( 0.0, 1.0 ); 43 point2 = Point( 1.0, 1.0 ); 44 point3 = Point( 1.0, 0.0 ); 45 point4 = Point( 0.0, 0.0 ); 46 } // end else 47 } // end function setcoord double Rectangle::length() 50 { 51 double side1 = fabs( point4.gety() - point1.gety() ); // get side1 52 double side2 = fabs( point2.getx() - point1.getx() ); // get side2 53 double length = ( side1 > side2? side1 : side2 ); 54 return length; 55 } // end function length double Rectangle::width() 58 { 59 double side1 = fabs( point4.gety() - point1.gety() ); // get side1 60 double side2 = fabs( point2.getx() - point1.getx() ); // get side2 61 double width = ( side1 < side2? side1 : side2 ); 62 return width; 63 } // end function width void Rectangle::perimeter() 66 { 67 cout << fixed << "\nthe perimeter is: " << setprecision( 1 ) 68 << 2 * ( length() + width() ) << endl; 69 } // end function perimeter void Rectangle::area() 72 { 73 cout << fixed << "The area is: " << setprecision( 1 ) 74 << length() * width() << endl; 75 } // end function area bool Rectangle::square()

34 Solutions { 79 return ( fabs( point4.gety() - point1.gety() ) == 80 fabs( point2.getx() - point1.getx() ) ); 81 } // end function square 1 // Exercise 9.12 Solution: Ex09_12.cpp 2 #include <iostream> 3 using std::cout; 4 5 #include "Rectangle.h" // include definition of class Rectangle 6 7 int main() 8 { 9 Point w( 1.0, 1.0 ); 10 Point x( 5.0, 1.0 ); 11 Point y( 5.0, 3.0 ); 12 Point z( 1.0, 3.0 ); 13 Point j( 0.0, 0.0 ); 14 Point k( 1.0, 0.0 ); 15 Point m( 1.0, 1.0 ); 16 Point n( 0.0, 1.0 ); 17 Point v( 99.0, -2.3 ); Rectangle rectangles[ 4 ]; // array stores four rectangles // output rectangles 22 for ( int i = 0; i < 4; i++ ) 23 { 24 cout << "Rectangle" << i + 1 << ":\n"; switch ( i ) // initialize four different rectangles 27 { 28 case 0: // first rectangle 29 rectangles[ i ] = Rectangle( z, y, x, w ); 30 break; 31 case 1: // second rectangle 32 rectangles[ i ] = Rectangle( j, k, m, n ); 33 break; 34 case 2: // third rectangle 35 rectangles[ i ] = Rectangle( w, x, m, n ); 36 break; 37 case 3: // fourth rectangle 38 rectangles[ i ] = Rectangle( v, x, y, z ); 39 break; 40 } // end switch cout << "length = " << rectangles[ i ].length(); 43 cout << "\nwidth = " << rectangles[ i ].width(); 44 rectangles[ i ].perimeter(); 45 rectangles[ i ].area(); 46 cout << "The rectangle " 47 << ( rectangles[ i ].square()? "is" : "is not" ) 48 << " a square.\n"; 49 } // end for

EE 152 Advanced Programming LAB 7

EE 152 Advanced Programming LAB 7 EE 152 Advanced Programming LAB 7 1) Create a class called Rational for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private data of

More information

Classes: A Deeper Look, Part 2

Classes: A Deeper Look, Part 2 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UEE1303(1070) S12: Object-Oriented Programming Constant Pointer and Class

UEE1303(1070) S12: Object-Oriented Programming Constant Pointer and Class UEE1303(1070) S12: Object-Oriented Programming Constant Pointer and Class What you will learn from Lab 4 In this laboratory, you will learn how to use const to identify constant pointer and the basic of

More information

Introduction to Classes

Introduction to Classes Introduction to Classes Procedural and Object-Oriented Programming Procedural and Object-Oriented Programming Procedural programming focuses on the process/actions that occur in a program Object-Oriented

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

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

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

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

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

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

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

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

Page 1 of 5. *** person.cpp *** #include "person.h" #include <string> #include <iostream> using namespace std; *** person.h ***

Page 1 of 5. *** person.cpp *** #include person.h #include <string> #include <iostream> using namespace std; *** person.h *** #ifndef PERSON_H #define PERSON_H #include "date.h" *** person.h *** class Person // constructors Person( ); Person( const string &name, const int id ); Person( const string &name, const int id, const

More information

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming Chapter 13: Introduction to Classes 1 13.1 Procedural and Object-Oriented Programming 2 Procedural and Object-Oriented Programming Procedural programming focuses on the process/actions that occur in a

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

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

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

Namespaces and Class Hierarchies

Namespaces and Class Hierarchies and 1 2 3 MCS 360 Lecture 9 Introduction to Data Structures Jan Verschelde, 13 September 2010 and 1 2 3 Suppose we need to store a point: 1 data: integer coordinates; 2 functions: get values for the coordinates

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: 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

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

C++ As A Better C Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan. C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2013 Fall Outline 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.5

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

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

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

Software Development With Java CSCI

Software Development With Java CSCI Software Development With Java CSCI-3134-01 D R. R A J S I N G H Outline Week 8 Controlling Access to Members this Reference Default and No-Argument Constructors Set and Get Methods Composition, Enumerations

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

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

! 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

! 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

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

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank 1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A. integer B 1.427E3 B. double D "Oct" C. character B -63.29 D. string F #Hashtag

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

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

! 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

Scope. Scope is such an important thing that we ll review what we know about scope now:

Scope. Scope is such an important thing that we ll review what we know about scope now: Scope Scope is such an important thing that we ll review what we know about scope now: Local (block) scope: A name declared within a block is accessible only within that block and blocks enclosed by it,

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

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game

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

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

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

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number Generation

More information

第三章习题答案 // include definition of class GradeBook from GradeBook.h #include "GradeBook.h"

第三章习题答案 // include definition of class GradeBook from GradeBook.h #include GradeBook.h 第三章习题答案 3.11 // Exercise 3.11 Solution: GradeBook.h // Definition of GradeBook class that stores an instructor's name. #include // program uses C++ standard string class using std::string; //

More information

Chapter 19 C++ Inheritance

Chapter 19 C++ Inheritance Chapter 19 C++ Inheritance Angela Chih-Wei i Tang Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 19.11 Introduction ti 19.2 Inheritance: Base Classes

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

! 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

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A. Engineering Problem Solving With C++ 4th Edition Etter TEST BANK Full clear download (no error formating) at: https://testbankreal.com/download/engineering-problem-solving-with-c-4thedition-etter-test-bank/

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

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

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

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

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++ Chapter 3 - Functions 1 Chapter 3 - Functions 2 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3. Functions 3.5 Function Definitions 3.6 Function Prototypes 3. Header Files 3.8

More information

SFU CMPT Topic: Classes

SFU CMPT Topic: Classes SFU CMPT-212 2008-1 1 Topic: Classes SFU CMPT-212 2008-1 Topic: Classes Ján Maňuch E-mail: jmanuch@sfu.ca Friday 15 th February, 2008 SFU CMPT-212 2008-1 2 Topic: Classes Encapsulation Using global variables

More information

UEE1303(1070) S12: Object-Oriented Programming Constructors and Destructors

UEE1303(1070) S12: Object-Oriented Programming Constructors and Destructors UEE1303(1070) S12: Object-Oriented Programming Constructors and Destructors What you will learn from Lab 5 In this laboratory, you will learn how to use constructor and copy constructor to create an object

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

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

Ch 2 ADTs and C++ Classes

Ch 2 ADTs and C++ Classes Ch 2 ADTs and C++ Classes Object Oriented Programming & Design Constructing Objects Hiding the Implementation Objects as Arguments and Return Values Operator Overloading 1 Object-Oriented Programming &

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

Object-Based Programming (Deitel chapter 8)

Object-Based Programming (Deitel chapter 8) Object-Based Programming (Deitel chapter 8) 1 Plan 2 Introduction Implementing a Time Abstract Data Type with a Class Class Scope Controlling Access to Members Referring to the Current Object s Members

More information

Chapter 19 - C++ Inheritance

Chapter 19 - C++ Inheritance Chapter 19 - C++ Inheritance 19.1 Introduction 19.2 Inheritance: Base Classes and Derived Classes 19.3 Protected Members 19.4 Casting Base-Class Pointers to Derived-Class Pointers 19.5 Using Member Functions

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming Section 3: Classes and inheritance (1) Piotr Mielecki, Ph. D. piotr.mielecki@pwr.edu.pl pmielecki@gmail.com Class vs. structure declaration Inheritance and access specifiers

More information

(3) Some memory that holds a value of a given type. (8) The basic unit of addressing in most computers.

(3) Some memory that holds a value of a given type. (8) The basic unit of addressing in most computers. CS 7A Final Exam - Fall 206 - Final Exam Solutions 2/3/6. Write the number of the definition on the right next to the term it defines. () Defining two functions or operators with the same name but different

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

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

Programming II Lecture 2 Structures and Classes

Programming II Lecture 2 Structures and Classes 3. struct Rectangle { 4. double length; 5. double width; 6. }; 7. int main() 8. { Rectangle R={12.5,7}; 9. cout

More information