Download presentation
Presentation is loading. Please wait.
1
CISC181 Introduction to Computer Science Dr
CISC181 Introduction to Computer Science Dr. McCoy Lecture 18 October 29, 2009
2
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Pointer Assignments Pointer variables can be "assigned": int *p1, *p2; p2 = p1; Assigns one pointer to another "Make p2 point to where p1 points" Do not confuse with: *p1 = *p2; Assigns "value pointed to" by p1, to "value pointed to" by p2 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
3
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Pointer Assignments Graphic: Display Uses of the Assignment Operator with Pointer Variables Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
4
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
The new Operator Since pointers can refer to variables… No "real" need to have a standard identifier Can dynamically allocate variables Operator new creates variables No identifiers to refer to them Just a pointer! p1 = new int; Creates new "nameless" variable, and assigns p1 to "point to" it Can access with *p1 Use just like ordinary variable Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
5
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Basic Pointer Manipulations Example: Display Basic Pointer Manipulations (1 of 2) Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
6
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Basic Pointer Manipulations Example: Display Basic Pointer Manipulations (2 of 2) Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
7
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Basic Pointer Manipulations Graphic: Display Explanation of Display 10.2 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
8
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
More on new Operator Creates new dynamic variable Returns pointer to the new variable If type is class type: Constructor is called for new object Can invoke different constructor with initializer arguments: MyClass *mcPtr; mcPtr = new MyClass(32.0, 17); Can still initialize non-class types: int *n; n = new int(17); //Initializes *n to 17 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
9
Pointers and Functions
Pointers are full-fledged types Can be used just like other types Can be function parameters Can be returned from functions Example: int* findOtherPointer(int* p); This function declaration: Has "pointer to an int" parameter Returns "pointer to an int" variable Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
10
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Memory Management Heap Also called "freestore" Reserved for dynamically-allocated variables All new dynamic variables consume memory in freestore If too many could use all freestore memory Future "new" operations will fail if freestore is "full" Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
11
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Checking new Success Older compilers: Test if null returned by call to new: int *p; p = new int; if (p == NULL) { cout << "Error: Insufficient memory.\n"; exit(1); } If new succeeded, program continues Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
12
new Success – New Compiler
Newer compilers: If new operation fails: Program terminates automatically Produces error message Still good practice to use NULL check Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
13
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Freestore Size Varies with implementations Typically large Most programs won’t use all memory Memory management Still good practice Solid software engineering principle Memory IS finite Regardless of how much there is! Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
14
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
delete Operator De-allocate dynamic memory When no longer needed Returns memory to freestore Example: int *p; p = new int(5); … //Some processing… delete p; De-allocates dynamic memory "pointed to by pointer p" Literally "destroys" memory Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
15
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Dangling Pointers delete p; Destroys dynamic memory But p still points there! Called "dangling pointer" If p is then dereferenced ( *p ) Unpredicatable results! Often disastrous! Avoid dangling pointers Assign pointer to NULL after delete: delete p; p = NULL; Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
16
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Dynamic Arrays Array variables Really pointer variables! Standard array Fixed size Dynamic array Size not specified at programming time Determined while program running Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
17
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Array Variables Recall: arrays stored in memory addresses, sequentially Array variable "refers to" first indexed variable So array variable is a kind of pointer variable! Example: int a[10]; int * p; a and p are both pointer variables! Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
18
Array Variables Pointers
Recall previous example: int a[10]; typedef int* IntPtr; IntPtr p; a and p are pointer variables Can perform assignments: p = a; // Legal. p now points where a points To first indexed variable of array a a = p; // ILLEGAL! Array pointer is CONSTANT pointer! Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
19
Array Variables Pointers
Array variable int a[10]; MORE than a pointer variable "const int *" type Array was allocated in memory already Variable a MUST point there…always! Cannot be changed! In contrast to ordinary pointers Which can (& typically do) change Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
20
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Dynamic Arrays Array limitations Must specify size first May not know until program runs! Must "estimate" maximum size needed Sometimes OK, sometimes not "Wastes" memory Dynamic arrays Can grow and shrink as needed Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
21
Creating Dynamic Arrays
Very simple! Use new operator Dynamically allocate with pointer variable Treat like standard arrays Example: typedef double * DoublePtr; DoublePtr d; d = new double[10]; //Size in brackets Creates dynamically allocated array variable d, with ten elements, base type double Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
22
Deleting Dynamic Arrays
Allocated dynamically at run-time So should be destroyed at run-time Simple again. Recall Example: d = new double[10]; … //Processing delete [] d; De-allocates all memory for dynamic array Brackets indicate "array" is there Recall: d still points there! Should set d = NULL; Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
23
Function that Returns an Array
Array type NOT allowed as return-type of function Example: int [] someFunction(); // ILLEGAL! Instead return pointer to array base type: int* someFunction(); // LEGAL! Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
24
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Destructor Need Dynamically-allocated variables Do not go away until "deleted" If pointers are only private member data They dynamically allocate "real" data In constructor Must have means to "deallocate" when object is destroyed Answer: destructor! Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
25
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Destructors Opposite of constructor Automatically called when object is out-of-scope Default version only removes ordinary variables, not dynamic variables Defined like constructor, just add ~ MyClass::~MyClass() { //Perform delete clean-up duties } Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
26
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copy Constructors Automatically called when: Class object declared and initialized to other object When function returns class type object When argument of class type is "plugged in" as actual argument to call-by-value parameter Requires "temporary copy" of object Copy constructor creates it Default copy constructor Like default "=", performs member-wise copy Pointers write own copy constructor! Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
27
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Summary 1 Pointer is memory address Provides indirect reference to variable Dynamic variables Created and destroyed while program runs Freestore Memory storage for dynamic variables Dynamically allocated arrays Size determined as program runs Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
28
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Summary 2 Class destructor Special member function Automatically destroys objects Copy constructor Single argument member function Called automatically when temp copy needed Assignment operator Must be overloaded as member function Returns reference for chaining Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
29
Go over Homework 6.6 – Complex Class
Header file contains class definition – complex.h – note preprocessor directives so don’t load it more than once! Class implementation complex.cc – note preprocessor directives for loading header; must be compiled. Driver Program (19-complex.cc) – note preprocessor directives for loading header. ~/mccoy/Class/cisc181/examples
30
6.5 Implementing a Time Abstract Data Type with a class
Advantages of using classes Simplify programming Interfaces Hide implementation Software reuse Composition (aggregation) Class objects included as members of other classes Inheritance New classes derived from old
31
6.6 Class Scope and Accessing Class Members
Data members, member functions Within class scope Class members Immediately accessible by all member functions Referenced by name Outside class scope Referenced through handles Object name, reference to object, pointer to object File scope Nonmember functions
32
6.6 Class Scope and Accessing Class Members
Function scope Variables declared in member function Only known to function Variables with same name as class-scope variables Class-scope variable “hidden” Access with scope resolution operator (::) ClassName::classVariableName Variables only known to function they are defined in Variables are destroyed after function completion
33
6.6 Class Scope and Accessing Class Members
Operators to access class members Identical to those for structs Dot member selection operator (.) Object Reference to object Arrow member selection operator (->) Pointers
34
// Fig. 6.4: fig06_04.cpp // Demonstrating the class member access operators . and -> // // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA! #include <iostream> 6 using std::cout; using std::endl; 9 10 // class Count definition 11 class Count { 12 13 public: int x; 15 void print() { cout << x << endl; } 20 21 }; // end class Count 22 fig06_04.cpp (1 of 2) Data member x public to illustrate class member access operators; typically data members private.
35
fig06_04.cpp (2 of 2) fig06_04.cpp output (1 of 1)
23 int main() 24 { Count counter; // create counter object Count *counterPtr = &counter; // create pointer to counter Count &counterRef = counter; // create reference to counter 28 cout << "Assign 1 to x and print using the object's name: "; counter.x = 1; // assign 1 to data member x counter.print(); // call member function print 32 cout << "Assign 2 to x and print using a reference: "; counterRef.x = 2; // assign 2 to data member x counterRef.print(); // call member function print 36 cout << "Assign 3 to x and print using a pointer: "; counterPtr->x = 3; // assign 3 to data member x counterPtr->print(); // call member function print 40 return 0; 42 43 } // end main fig06_04.cpp (2 of 2) fig06_04.cpp output (1 of 1) Use dot member selection operator for counter object. Use dot member selection operator for counterRef reference to object. Use arrow member selection operator for counterPtr pointer to object. Assign 1 to x and print using the object's name: 1 Assign 2 to x and print using a reference: 2 Assign 3 to x and print using a pointer: 3
36
Another Example Rational Number class (in same directory)
37
6.7 Separating Interface from Implementation
Advantage Easier to modify programs Disadvantage Header files Portions of implementation Inline member functions Hints about other implementation private members Can hide more with proxy class
38
6.7 Separating Interface from Implementation
Header files Class definitions and function prototypes Included in each file using class #include File extension .h Source-code files Member function definitions Same base name Convention Compiled and linked
39
Preprocessor code to prevent multiple inclusions.
// Fig. 6.5: time1.h // Declaration of class Time. // Member functions are defined in time1.cpp 4 // prevent multiple inclusions of header file #ifndef TIME1_H #define TIME1_H 8 // Time abstract data type definition 10 class Time { 11 12 public: Time(); // constructor void setTime( int, int, int ); // set hour, minute, second void printUniversal(); // print universal-time format void printStandard(); // print standard-time format 17 18 private: int hour; // (24-hour clock format) int minute; // int second; // 22 23 }; // end class Time 24 25 #endif Preprocessor code to prevent multiple inclusions. time1.h (1 of 1) Code between these directives not included if name TIME1_H already defined. “If not defined” Preprocessor directive defines name TIME1_H. Naming convention: header file name with underscore replacing period.
40
Include header file time1.h.
// Fig. 6.6: time1.cpp // Member-function definitions for class Time. #include <iostream> 4 using std::cout; 6 #include <iomanip> 8 using std::setfill; 10 using std::setw; 11 12 // include definition of class Time from time1.h 13 #include "time1.h" 14 15 // Time constructor initializes each data member to zero. 16 // Ensures all Time objects start in a consistent state. 17 Time::Time() 18 { hour = minute = second = 0; 20 21 } // end Time constructor 22 time1.cpp (1 of 3) Include header file time1.h. Name of header file enclosed in quotes; angle brackets cause preprocessor to assume header part of C++ Standard Library.
41
23 // Set new Time value using universal time. Perform validity
24 // checks on the data values. Set invalid values to zero. 25 void Time::setTime( int h, int m, int s ) 26 { hour = ( h >= 0 && h < 24 ) ? h : 0; minute = ( m >= 0 && m < 60 ) ? m : 0; second = ( s >= 0 && s < 60 ) ? s : 0; 30 31 } // end function setTime 32 33 // print Time in universal format 34 void Time::printUniversal() 35 { cout << setfill( '0' ) << setw( 2 ) << hour << ":" << setw( 2 ) << minute << ":" << setw( 2 ) << second; 39 40 } // end function printUniversal 41 time1.cpp (2 of 3)
42
time1.cpp (3 of 3) 42 // print Time in standard format
43 void Time::printStandard() 44 { cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ":" << setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 ) << second << ( hour < 12 ? " AM" : " PM" ); 49 50 } // end function printStandard time1.cpp (3 of 3)
43
// Fig. 6.7: fig06_07.cpp // Program to test class Time. // NOTE: This file must be compiled with time1.cpp. #include <iostream> 5 using std::cout; using std::endl; 8 // include definition of class Time from time1.h 10 #include "time1.h" 11 12 int main() 13 { Time t; // instantiate object t of class Time 15 // output Time object t's initial values cout << "The initial universal time is "; t.printUniversal(); // 00:00:00 cout << "\nThe initial standard time is "; t.printStandard(); // 12:00:00 AM 21 t.setTime( 13, 27, 6 ); // change time 23 fig06_07.cpp (1 of 2) Include header file time1.h to ensure correct creation/manipulation and determine size of Time class object.
44
fig06_07.cpp (2 of 2) fig06_07.cpp output (1 of 1)
// output Time object t's new values cout << "\n\nUniversal time after setTime is "; t.printUniversal(); // 13:27:06 cout << "\nStandard time after setTime is "; t.printStandard(); // 1:27:06 PM 29 t.setTime( 99, 99, 99 ); // attempt invalid settings 31 // output t's values after specifying invalid values cout << "\n\nAfter attempting invalid settings:" << "\nUniversal time: "; t.printUniversal(); // 00:00:00 cout << "\nStandard time: "; t.printStandard(); // 12:00:00 AM cout << endl; 39 return 0; 41 42 } // end main fig06_07.cpp (2 of 2) fig06_07.cpp output (1 of 1) The initial universal time is 00:00:00 The initial standard time is 12:00:00 AM Universal time after setTime is 13:27:06 Standard time after setTime is 1:27:06 PM
45
6.8 Controlling Access to Members
Access modes private Default access mode Accessible to member functions and friends public Accessible to any function in program with handle to class object protected Chapter 9
46
// Fig. 6.8: fig06_08.cpp // Demonstrate errors resulting from attempts // to access private class members. #include <iostream> 5 using std::cout; 7 // include definition of class Time from time1.h #include "time1.h" 10 11 int main() 12 { Time t; // create Time object 14 15 t.hour = 7; // error: 'Time::hour' is not accessible 17 // error: 'Time::minute' is not accessible cout << "minute = " << t.minute; 20 return 0; 22 23 } // end main fig06_08.cpp (1 of 1) Recall data member hour is private; attempts to access private members results in error. Data member minute also private; attempts to access private members produces error.
47
Errors produced by attempting to access private members.
D:\cpphtp4_examples\ch06\Fig6_06\Fig06_06.cpp(16) : error C2248: 'hour' : cannot access private member declared in class 'Time' D:\cpphtp4_examples\ch06\Fig6_06\Fig06_06.cpp(19) : error C2248: 'minute' : cannot access private member declared in class 'Time' Errors produced by attempting to access private members. fig06_08.cpp output (1 of 1)
48
6.8 Controlling Access to Members
Class member access Default private Explicitly set to private, public, protected struct member access Default public Access to class’s private data Controlled with access functions (accessor methods) Get function Read private data Set function Modify private data
49
6.9 Access Functions and Utility Functions
public Read/display data Predicate functions Check conditions Utility functions (helper functions) private Support operation of public member functions Not intended for direct client use
50
Set access function performs validity checks.
// Fig. 6.9: salesp.h // SalesPerson class definition. // Member functions defined in salesp.cpp. #ifndef SALESP_H #define SALESP_H 6 class SalesPerson { 8 public: SalesPerson(); // constructor void getSalesFromUser(); // input sales from keyboard void setSales( int, double ); // set sales for a month void printAnnualSales(); // summarize and print sales 14 15 private: double totalAnnualSales(); // utility function double sales[ 12 ]; // 12 monthly sales figures 18 19 }; // end class SalesPerson 20 21 #endif salesp.h (1 of 1) Set access function performs validity checks. private utility function.
51
salesp.cpp (1 of 3) 1 // Fig. 6.10: salesp.cpp
// Member functions for class SalesPerson. #include <iostream> 4 using std::cout; using std::cin; using std::endl; using std::fixed; 9 10 #include <iomanip> 11 12 using std::setprecision; 13 14 // include SalesPerson class definition from salesp.h 15 #include "salesp.h" 16 17 // initialize elements of array sales to 0.0 18 SalesPerson::SalesPerson() 19 { for ( int i = 0; i < 12; i++ ) sales[ i ] = 0.0; 22 23 } // end SalesPerson constructor 24 salesp.cpp (1 of 3)
52
Set access function performs validity checks.
25 // get 12 sales figures from the user at the keyboard 26 void SalesPerson::getSalesFromUser() 27 { double salesFigure; 29 for ( int i = 1; i <= 12; i++ ) { cout << "Enter sales amount for month " << i << ": "; cin >> salesFigure; setSales( i, salesFigure ); 34 } // end for 36 37 } // end function getSalesFromUser 38 39 // set one of the 12 monthly sales figures; function subtracts 40 // one from month value for proper subscript in sales array 41 void SalesPerson::setSales( int month, double amount ) 42 { // test for valid month and amount values if ( month >= 1 && month <= 12 && amount > 0 ) sales[ month - 1 ] = amount; // adjust for subscripts 0-11 46 else // invalid month or amount value cout << "Invalid month or sales figure" << endl; salesp.cpp (2 of 3) Set access function performs validity checks.
53
49 50 } // end function setSales 51 52 // print total annual sales (with help of utility function) 53 void SalesPerson::printAnnualSales() 54 { cout << setprecision( 2 ) << fixed << "\nThe total annual sales are: $" << totalAnnualSales() << endl; // call utility function 58 59 } // end function printAnnualSales 60 61 // private utility function to total annual sales 62 double SalesPerson::totalAnnualSales() 63 { double total = 0.0; // initialize total 65 for ( int i = 0; i < 12; i++ ) // summarize sales results total += sales[ i ]; 68 return total; 70 71 } // end function totalAnnualSales salesp.cpp (3 of 3) private utility function to help function printAnnualSales; encapsulates logic of manipulating sales array.
54
// Fig. 6.11: fig06_11.cpp // Demonstrating a utility function. // Compile this program with salesp.cpp 4 // include SalesPerson class definition from salesp.h #include "salesp.h" 7 int main() { SalesPerson s; // create SalesPerson object s 11 s.getSalesFromUser(); // note simple sequential code; no s.printAnnualSales(); // control structures in main 14 return 0; 16 17 } // end main fig06_11.cpp (1 of 1) Simple sequence of member function calls; logic encapsulated in member functions.
55
fig06_11.cpp output (1 of 1) Enter sales amount for month 1: 5314.76
The total annual sales are: $ fig06_11.cpp output (1 of 1)
56
6.10 Initializing Class Objects: Constructors
Initialize data members Or can set later Same name as class No return type Initializers Passed as arguments to constructor In parentheses to right of class name before semicolon Class-type ObjectName( value1,value2,…);
57
6.11 Using Default Arguments with Constructors
Can specify default arguments Default constructors Defaults all arguments OR Explicitly requires no arguments Can be invoked with no arguments Only one per class
58
Default constructor specifying all arguments.
// Fig. 6.12: time2.h // Declaration of class Time. // Member functions defined in time2.cpp. 4 // prevent multiple inclusions of header file #ifndef TIME2_H #define TIME2_H 8 // Time abstract data type definition 10 class Time { 11 12 public: Time( int = 0, int = 0, int = 0); // default constructor void setTime( int, int, int ); // set hour, minute, second void printUniversal(); // print universal-time format void printStandard(); // print standard-time format 17 18 private: int hour; // (24-hour clock format) int minute; // int second; // 22 23 }; // end class Time 24 25 #endif time2.h (1 of 1) Default constructor specifying all arguments.
59
Constructor calls setTime to validate passed (or default) values.
// Fig. 6.13: time2.cpp // Member-function definitions for class Time. #include <iostream> 4 using std::cout; 6 #include <iomanip> 8 using std::setfill; 10 using std::setw; 11 12 // include definition of class Time from time2.h 13 #include "time2.h" 14 15 // Time constructor initializes each data member to zero; 16 // ensures all Time objects start in a consistent state 17 Time::Time( int hr, int min, int sec ) 18 { setTime( hr, min, sec ); // validate and set time 20 21 } // end Time constructor 22 time2.cpp (1 of 3) Constructor calls setTime to validate passed (or default) values.
60
23 // set new Time value using universal time, perform validity
24 // checks on the data values and set invalid values to zero 25 void Time::setTime( int h, int m, int s ) 26 { hour = ( h >= 0 && h < 24 ) ? h : 0; minute = ( m >= 0 && m < 60 ) ? m : 0; second = ( s >= 0 && s < 60 ) ? s : 0; 30 31 } // end function setTime 32 33 // print Time in universal format 34 void Time::printUniversal() 35 { cout << setfill( '0' ) << setw( 2 ) << hour << ":" << setw( 2 ) << minute << ":" << setw( 2 ) << second; 39 40 } // end function printUniversal 41 time2.cpp (2 of 3)
61
time2.cpp (3 of 3) 42 // print Time in standard format
43 void Time::printStandard() 44 { cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ":" << setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 ) << second << ( hour < 12 ? " AM" : " PM" ); 49 50 } // end function printStandard time2.cpp (3 of 3)
62
Initialize Time objects using default arguments.
// Fig. 6.14: fig06_14.cpp // Demonstrating a default constructor for class Time. #include <iostream> 4 using std::cout; using std::endl; 7 // include definition of class Time from time2.h #include "time2.h" 10 11 int main() 12 { Time t1; // all arguments defaulted Time t2( 2 ); // minute and second defaulted Time t3( 21, 34 ); // second defaulted Time t4( 12, 25, 42 ); // all values specified Time t5( 27, 74, 99 ); // all bad values specified 18 cout << "Constructed with:\n\n" << "all default arguments:\n "; t1.printUniversal(); // 00:00:00 cout << "\n "; t1.printStandard(); // 12:00:00 AM 24 fig06_14.cpp (1 of 2) Initialize Time objects using default arguments. Initialize Time object with invalid values; validity checking will set values to 0.
63
t5 constructed with invalid arguments; values set to 0.
cout << "\n\nhour specified; default minute and second:\n "; t2.printUniversal(); // 02:00:00 cout << "\n "; t2.printStandard(); // 2:00:00 AM 29 cout << "\n\nhour and minute specified; default second:\n "; t3.printUniversal(); // 21:34:00 cout << "\n "; t3.printStandard(); // 9:34:00 PM 34 cout << "\n\nhour, minute, and second specified:\n "; t4.printUniversal(); // 12:25:42 cout << "\n "; t4.printStandard(); // 12:25:42 PM 39 cout << "\n\nall invalid values specified:\n "; t5.printUniversal(); // 00:00:00 cout << "\n "; t5.printStandard(); // 12:00:00 AM cout << endl; 45 return 0; 47 48 } // end main fig06_14.cpp (2 of 2) t5 constructed with invalid arguments; values set to 0.
64
fig06_14.cpp output (1 of 1) Constructed with: all default arguments:
all default arguments: 00:00:00 12:00:00 AM hour specified; default minute and second: 02:00:00 2:00:00 AM hour and minute specified; default second: 21:34:00 9:34:00 PM hour, minute, and second specified: 12:25:42 12:25:42 PM all invalid values specified: fig06_14.cpp output (1 of 1)
65
6.12 Destructors Destructors Special member function
Same name as class Preceded with tilde (~) No arguments No return value Cannot be overloaded Performs “termination housekeeping” Before system reclaims object’s memory Reuse memory for new objects No explicit destructor Compiler creates “empty” destructor”
66
6.14 Using Set and Get Functions
Set functions Perform validity checks before modifying private data Notify if invalid values Indicate with return values Get functions “Query” functions Control format of data returned
67
time3.h (1 of 2) Set functions. Get functions. 1 // Fig. 6.18: time3.h
// Declaration of class Time. // Member functions defined in time3.cpp 4 // prevent multiple inclusions of header file #ifndef TIME3_H #define TIME3_H 8 class Time { 10 11 public: Time( int = 0, int = 0, int = 0 ); // default constructor 13 // set functions void setTime( int, int, int ); // set hour, minute, second void setHour( int ); // set hour void setMinute( int ); // set minute void setSecond( int ); // set second 19 // get functions int getHour(); // return hour int getMinute(); // return minute int getSecond(); // return second 24 time3.h (1 of 2) Set functions. Get functions.
68
25 void printUniversal(); // output universal-time format
void printStandard(); // output standard-time format 27 28 private: int hour; // (24-hour clock format) int minute; // int second; // 32 33 }; // end clas Time 34 35 #endif time3.h (2 of 2)
69
time3.cpp (1 of 4) 1 // Fig. 6.19: time3.cpp
// Member-function definitions for Time class. #include <iostream> 4 using std::cout; 6 #include <iomanip> 8 using std::setfill; 10 using std::setw; 11 12 // include definition of class Time from time3.h 13 #include "time3.h" 14 15 // constructor function to initialize private data; 16 // calls member function setTime to set variables; 17 // default values are 0 (see class definition) 18 Time::Time( int hr, int min, int sec ) 19 { setTime( hr, min, sec ); 21 22 } // end Time constructor 23 time3.cpp (1 of 4)
70
Call set functions to perform validity checking.
24 // set hour, minute and second values 25 void Time::setTime( int h, int m, int s ) 26 { setHour( h ); setMinute( m ); setSecond( s ); 30 31 } // end function setTime 32 33 // set hour value 34 void Time::setHour( int h ) 35 { hour = ( h >= 0 && h < 24 ) ? h : 0; 37 38 } // end function setHour 39 40 // set minute value 41 void Time::setMinute( int m ) 42 { minute = ( m >= 0 && m < 60 ) ? m : 0; 44 45 } // end function setMinute 46 time3.cpp (2 of 4) Call set functions to perform validity checking. Set functions perform validity checks before modifying data.
71
Set function performs validity checks before modifying data.
47 // set second value 48 void Time::setSecond( int s ) 49 { second = ( s >= 0 && s < 60 ) ? s : 0; 51 52 } // end function setSecond 53 54 // return hour value 55 int Time::getHour() 56 { return hour; 58 59 } // end function getHour 60 61 // return minute value 62 int Time::getMinute() 63 { return minute; 65 66 } // end function getMinute 67 Set function performs validity checks before modifying data. time3.cpp (3 of 4) Get functions allow client to read data.
72
Get function allows client to read data. time3.cpp (4 of 4)
68 // return second value 69 int Time::getSecond() 70 { return second; 72 73 } // end function getSecond 74 75 // print Time in universal format 76 void Time::printUniversal() 77 { cout << setfill( '0' ) << setw( 2 ) << hour << ":" << setw( 2 ) << minute << ":" << setw( 2 ) << second; 81 82 } // end function printUniversal 83 84 // print Time in standard format 85 void Time::printStandard() 86 { cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ":" << setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 ) << second << ( hour < 12 ? " AM" : " PM" ); 91 92 } // end function printStandard Get function allows client to read data. time3.cpp (4 of 4)
73
Invoke set functions to set valid values.
// Fig. 6.20: fig06_20.cpp // Demonstrating the Time class set and get functions #include <iostream> 4 using std::cout; using std::endl; 7 // include definition of class Time from time3.h #include "time3.h" 10 11 void incrementMinutes( Time &, const int ); // prototype 12 13 int main() 14 { Time t; // create Time object 16 // set time using individual set functions t.setHour( 17 ); // set hour to valid value t.setMinute( 34 ); // set minute to valid value t.setSecond( 25 ); // set second to valid value 21 fig06_20.cpp (1 of 3) Invoke set functions to set valid values.
74
Attempt to set invalid values using set functions.
// use get functions to obtain hour, minute and second cout << "Result of setting all valid values:\n" << " Hour: " << t.getHour() << " Minute: " << t.getMinute() << " Second: " << t.getSecond(); 27 // set time using individual set functions t.setHour( 234 ); // invalid hour set to 0 t.setMinute( 43 ); // set minute to valid value t.setSecond( 6373 ); // invalid second set to 0 32 // display hour, minute and second after setting // invalid hour and second values cout << "\n\nResult of attempting to set invalid hour and" << " second:\n Hour: " << t.getHour() << " Minute: " << t.getMinute() << " Second: " << t.getSecond() << "\n\n"; 39 t.setTime( 11, 58, 0 ); // set time incrementMinutes( t, 3 ); // increment t's minute by 3 42 return 0; 44 45 } // end main 46 Attempt to set invalid values using set functions. fig06_20.cpp (2 of 3) Invalid values result in setting data members to 0. Modify data members using function setTime.
75
Using get functions to read data and set functions to modify data.
47 // add specified number of minutes to a Time object 48 void incrementMinutes( Time &tt, const int count ) 49 { cout << "Incrementing minute " << count << " times:\nStart time: "; tt.printStandard(); 53 for ( int i = 0; i < count; i++ ) { tt.setMinute( ( tt.getMinute() + 1 ) % 60 ); 56 if ( tt.getMinute() == 0 ) tt.setHour( ( tt.getHour() + 1 ) % 24); 59 cout << "\nminute + 1: "; tt.printStandard(); 62 } // end for 64 cout << endl; 66 67 } // end function incrementMinutes fig06_20.cpp (3 of 3) Using get functions to read data and set functions to modify data.
76
Result of setting all valid values:
Hour: 17 Minute: 34 Second: 25 Result of attempting to set invalid hour and second: Hour: 0 Minute: 43 Second: 0 Incrementing minute 3 times: Start time: 11:58:00 AM minute + 1: 11:59:00 AM minute + 1: 12:00:00 PM minute + 1: 12:01:00 PM fig06_20.cpp output (1 of 1) Attempting to set data members with invalid values results in error message and members set to 0.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.