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

Similar documents
Chapter 6: Classes and Data Abstraction

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>

57:017, Computers in Engineering C++ Classes

IS 0020 Program Design and Software Tools

Chapter 16: Classes and Data Abstraction

More C++ Classes. Systems Programming

Fundamentals of Programming Session 24

Classes: A Deeper Look

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools

Introduction to Programming session 24

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

Computer Programming with C++ (21)

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

A Deeper Look at Classes

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

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Classes: A Deeper Look. Systems Programming

Classes: A Deeper Look, Part 2

Computer Programming Class Members 9 th Lecture

Chapter 9 Classes : A Deeper Look, Part 1

Classes and Data Abstraction. Topic 5

Classes and Data Abstraction

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

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

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

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

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

Chapter 17 - C++ Classes: Part II

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

OBJECT ORIENTED PROGRAMMING USING C++

Object Oriented Design

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

! 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

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

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

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

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

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

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

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

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

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

Classes: A Deeper Look, Part 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 the following: - variables AND

Lecture 5. Function Pointers

Classes and Data Abstraction. Topic 5

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

Object-Based Programming (Deitel chapter 8)

Object Oriented Design

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

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

Introduction to C++ Introduction to C++ 1

Short Notes of CS201

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

CS201 - Introduction to Programming Glossary By

G205 Fundamentals of Computer Engineering. CLASS 3, Wed. Sept Stefano Basagni Fall 2004 M-W, 1:30pm-3:10pm

In this chapter, you will learn about: Pointers. Dynamic Arrays. Introduction Computer Science 1 CS 23021

Functions and Recursion

Chapter 9. Pointers and Dynamic Arrays

1 OBJECT-BASED PROGRAMMING CHAPTER 8

Chapter Overview. Pointers and Dynamic Arrays. Pointers. Pointers. Declaring Pointers. Pointers Tell Where To Find A Variable. 9.

Cpt S 122 Data Structures. Introduction to C++ Part II

Introduction to C++ Systems Programming

Lecture 18 Tao Wang 1

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction

Computer Programming C++ Classes and Objects 6 th Lecture

Pointers and Dynamic Arrays

CS201 Latest Solved MCQs

III. Classes (Chap. 3)

QUIZ. What is wrong with this code that uses default arguments?

CS3157: Advanced Programming. Outline

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Fast Introduction to Object Oriented Programming and C++

AN OVERVIEW OF C++ 1

Chapter 18 - C++ Operator Overloading

Object-Based Programming

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

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

Chapter 7: Classes Part II

CS304 Object Oriented Programming Final Term

Operator Overloading in C++ Systems Programming

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Chapter 10 Introduction to Classes

Homework #3 CS2255 Fall 2012

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

EL2310 Scientific Programming

Constructor - example

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

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

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

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

G52CPP C++ Programming Lecture 13

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

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

Operator Overloading

How to engineer a class to separate its interface from its implementation and encourage reuse.

Transcription:

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 to where p1 points" Do not confuse with: *p1 = *p2; Assigns "value pointed to" by p1, to "value pointed to" by p2 1 Copyright 2010 Pearson Addison Wesley. 10 2 Pointer Assignments Graphic: Display 10.1 Uses of the Assignment Operator with Pointer Variables 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. 10 3 Copyright 2010 Pearson Addison Wesley. 10 Basic Pointer Manipulations Example: Display 10.2 Basic Pointer Manipulations (1 of 2) Basic Pointer Manipulations Example: Display 10.2 Basic Pointer Manipulations (2 of 2) Copyright 2010 Pearson Addison Wesley. All rights reserved. 10 5 Copyright 2010 Pearson Addison Wesley. All rights reserved. 10 6 1

Basic Pointer Manipulations Graphic: Display 10.3 Explanation of Display 10.2 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(.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. 10 7 Copyright 2010 Pearson Addison Wesley. 10 Pointers and Functions Memory Management 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 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. 10 9 Copyright 2010 Pearson Addison Wesley. 10 10 Checking new Success new Success New Compiler 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); } Newer compilers: If new operation fails: Program terminates automatically Produceserror error message Still good practice to use NULL check If new succeeded, program continues Copyright 2010 Pearson Addison Wesley. 10 Copyright 2010 Pearson Addison Wesley. 10 12 2

Freestore Size delete Operator 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! 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. 10 13 Copyright 2010 Pearson Addison Wesley. 10 1 Dangling Pointers Dynamic Arrays 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; 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. 10 15 Copyright 2010 Pearson Addison Wesley. 10 16 Array Variables Array Variables Pointers 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! 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. 10 17 Copyright 2010 Pearson Addison Wesley. 10 1 3

Array Variables Pointers Dynamic Arrays 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 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. 10 19 Copyright 2010 Pearson Addison Wesley. 10 20 Creating Dynamic Arrays Deleting 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 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. 10 21 Copyright 2010 Pearson Addison Wesley. 10 Function that Returns an Array Destructor Need Array type NOT allowed as return type of function Dynamically allocated variables Do not go away until "deleted" Example: int [] somefunction(); // ILLEGAL! Instead return pointer to array base type: int* somefunction(); // LEGAL! If pointers are only private member data They dynamically allocate "real" l"dt data In constructor Must have means to "deallocate" when object is destroyed Answer: destructor! Copyright 2010 Pearson Addison Wesley. 10 23 Copyright 2010 Pearson Addison Wesley. 10 2

Destructors Copy Constructors Opposite of constructor Automatically called when object is out of scope Default version only removes ordinary variables, not dynamic variables Automatically called when: 1. Class object declared and initialized to other object 2. When function returns class type object 3. When argument of class type is "plugged in" as actual argument to call by value parameter Defined like constructor, just add ~ MyClass::~MyClass() { //Perform delete clean up duties } 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. 10 25 Copyright 2010 Pearson Addison Wesley. 10 26 Summary 1 Summary 2 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 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. 10 27 Copyright 2010 Pearson Addison Wesley. 10 2 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/cisc11/examples 29 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 30 5

6.6 Class Scope and Accessing Class Members 31 6.6 Class Scope and Accessing Class Members Class scope 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 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 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 33 1 // Fig. 6.: fig06_0.cpp 2 // Demonstrating the class member access operators. and -> 3 // // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA! 5 #include <iostream> 6 7 using std::cout; using std::endl; 9 10 // class Count definition class Count { Data member x public to 12 illustrate class member access 13 public: operators; typically data 1 int x; members private. 15 16 void print() 17 { 1 cout << x << endl; 19 } fig06_0.cpp (1 of 2) 3 20 21 }; // end class Count 23 int main() 2 { 25 Count counter; // create counter object 26 Count *counterptr // create pointer to counter = &counter; 27 Count &counterref = counter; // Use create dot member reference selection to counter 2 29 operator for counter object. cout << "Assign 1 to x and print using the object's name: "; 30 counter.x = 1; // assign 1 to data member x 31 counter.print(); // call member Use function dot member printselection operator for counterref 33 cout << "Assign 2 to x and print using reference a reference: to object. "; 3 counterref.x = 2; // assign 2 to data member x 35 counterref.print(); // call member Use function arrow print member selection operator for counterptr 36 37 cout << "Assign 3 to x and print using pointer a pointer: to object. "; 3 counterptr->x = 3; // assign 3 to data member x 39 counterptr->print(); // call member function print fig06_0.cpp (2 of 2) fig06_0.cpp output (1 of 1) 35 Another Example Rational Number class (in same directory) 0 1 return 0; 2 3 } // end main 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 6

6.7 Separating Interface from Implementation 37 6.7 Separating Interface from Implementation 3 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 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 1 // Fig. 6.5: time1.h 2 // Declaration of class Time. 3 // Member functions are defined in time1.cpp Preprocessor code to prevent 5 multiple inclusions. // prevent multiple inclusions of header file 6 #ifndef TIME1_H 7 #define TIME1_H Code between these directives 9 // Time abstract data type definition not included if name 10 class Time { Naming directive defines TIME1_H name convention: TIME1_H. already defined. header file name with 12 public: 13 Time(); underscore replacing period. // constructor 1 void settime( // set hour, minute, int, int, int ); second 15 void printuniversal(); // print universal-time format 16 void printstandard(); // print standard-time format 17 1 private: 19 int hour; // 0-23 (2-hour clock format) 20 int minute; // 0-59 21 int second; // 0-59 time1.h (1 of 1) 39 1 // Fig. 6.6: time1.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> 5 using std::cout; 6 7 #include <iomanip> 9 using std::setfill; 10 using std::setw; Include header file time1.h. 12 // include definition of class Time from time1.h 13 #include "time1.h" 1 15 // Time constructor initializes each data member to zero. 16 // Ensures all Time objects Name start of in header a consistent file enclosed state. 17 Time::Time() in quotes; angle brackets 1 { cause preprocessor to assume 19 hour = minute = second = 0; header part of C++ Standard 20 Library. 21 } // end Time constructor time1.cpp (1 of 3) 0 23 }; // end class Time 2 25 #endif 23 // Set new Time value using universal time. Perform validity 2 // checks on the data values. Set invalid values to zero. 25 void Time::setTime( int h, int m, int s ) 26 { 27 hour = ( h >= 0 && h < 2 )? h : 0; 2 minute = ( m >= 0 && m < 60 )? m : 0; 29 second = ( s >= 0 && s < 60 )? s : 0; time1.cpp (2 of 3) 1 2 // print Time in standard format 3 void Time::printStandard() { 5 cout << ( ( hour == 0 hour == 12 )? 12 : hour % 12 ) 6 << ":" << setfill( '0' ) << setw( 2 ) << minute 7 << ":" << setw( 2 ) << second << ( hour < 12? " AM" : " PM" ); time1.cpp (3 of 3) 2 30 31 } // end function settime 9 50 } // end function printstandard 33 // print Time in universal format 3 void Time::printUniversal() 35 { 36 cout << setfill( '0' ) << setw( 2 ) << hour << ":" 37 << setw( 2 ) << minute << ":" 3 << setw( 2 ) << second; 39 0 } // end function printuniversal 1 7

1 // Fig. 6.7: fig06_07.cpp 2 // Program to test class Time. 3 // NOTE: This file must be compiled with time1.cpp. #include <iostream> 5 6 using std::cout; Include header file time1.h 7 using std::endl; 9 to ensure correct // include definition of class Time from creation/manipulation time1.h and 10 #include "time1.h" determine size of Time class object. 12 int main() 13 { 1 Time t; // instantiate object t of class Time 15 16 // output Time object t's initial values 17 cout << "The initial universal time is "; 1 t.printuniversal(); // 00:00:00 19 cout << "\nthe initial standard time is "; 20 t.printstandard(); // 12:00:00 AM 21 t.settime( 13, 27, 6 ); // change time fig06_07.cpp (1 of 2) 3 2 // output Time object t's new values 25 cout << "\n\nuniversal time after settime is "; 26 t.printuniversal(); // 13:27:06 27 cout << "\nstandard time after settime is "; 2 t.printstandard(); // 1:27:06 PM 29 30 t.settime( 99, 99, 99 ); // attempt invalid settings 31 // output t's values after specifying invalid values 33 cout << "\n\nafter attempting invalid settings:" 3 << "\nuniversal time: "; 35 t.printuniversal(); // 00:00:00 36 cout << "\nstandard time: "; 37 t.printstandard(); // 12:00:00 AM 3 cout << endl; 39 0 return 0; 1 2 // end main } The initial universal time is 00:00:00 The initial standard time is 12:00:00 AM fig06_07.cpp (2 of 2) fig06_07.cpp output (1 of 1) 23 Universal time after settime is 13:27:06 Standard time after settime is 1:27:06 PM 6. 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 5 1 // Fig. 6.: fig06_0.cpp 2 // Demonstrate errors resulting from attempts 3 // to access private class members. #include <iostream> fig06_0.cpp 5 (1 of 1) 6 using std::cout; 7 // include definition of class Time from time1.h 9 #include "time1.h" 10 int main() 12 { Recall data member hour is object 13 Time t; // create Time private; attempts to access 1 15 private members results in 16 t.hour = 7; // error: 'Time::hour' error. is not accessible Data member minute also 17 private; attempts to access 1 // error: 'Time::minute' is not accessible private members produces 19 cout << "minute = " << t.minute; error. 20 21 return 0; 6 23 } // end main D:\cpphtp_examples\ch06\Fig6_06\Fig06_06.cpp(16) : error C: 'hour' : cannot access private member declared in class 'Time' D:\cpphtp_examples\ch06\Fig6_06\Fig06_06.cpp(19) : error C: 'minute' : cannot access private member declared in class 'Time' fig06_0.cpp output (1 of 1) Errors produced by attempting to access private members. 7 6. Controlling Access to Members Class member access Default private Explicitly set to private, public, protected struct member access Default public Explicitly set to private, public, protected Access to class s private data Controlled with access functions (accessor methods) Get function Read private data Set function Modify private data

6.9 Access Functions and Utility Functions Access 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 9 1 // Fig. 6.9: salesp.h 2 // SalesPerson class definition. 3 // Member functions defined in salesp.cpp. #ifndef SALESP_H 5 #define SALESP_H 6 7 class SalesPerson { Set access function 9 public: performs validity 10 SalesPerson(); // constructorchecks. void getsalesfromuser(); // input sales from keyboard 12 void setsales( int, double // set sales for a month ); 13 void printannualsales(); private utility // summarize and print sales 1 function. 15 private: 16 double totalannualsales(); // utility function 17 double sales[ 12 ]; // 12 monthly sales figures 1 19 // end class SalesPerson }; 20 21 #endif salesp.h (1 of 1) 50 1 // Fig. 6.10: salesp.cpp 2 // Member functions for class SalesPerson. 3 #include <iostream> 5 using std::cout; 6 using std::cin; 7 using std::endl; using std::fixed; 9 10 #include <iomanip> 12 using std::setprecision; 13 1 // include SalesPerson class definition from salesp.h 15 #include "salesp.h" 16 17 // initialize elements of array sales to 0.0 1 SalesPerson::SalesPerson() 19 { 20 for ( int i = 0; i < 12; i++ ) 21 sales[ i ] = 0.0; salesp.cpp (1 of 3) 51 25 // get 12 sales figures from the user at the keyboard 26 void SalesPerson::getSalesFromUser() 27 { 2 double salesfigure; 29 30 for ( int i = 1; i <= 12; i++ ) { 31 cout << "Enter sales amount for month " << i << ": "; cin >> salesfigure; 33 setsales( i, salesfigure ); 3 35 } // end for 36 37 } // end function getsalesfromuser 3 39 // set one of the 12 monthly sales figures; function subtracts 0 // one from month value for proper subscript in sales array Set access function performs 1 void SalesPerson::setSales( int month, double amount ) validity checks. 2 { 3 // test for valid month and amount values if ( month >= 1 && month <= 12 && amount > 0 ) 5 sales[ month - 1 ] = amount; // adjust for subscripts 0- salesp.cpp (2 of 3) 52 23 } // end SalesPerson constructor 2 6 7 else // invalid month or amount value cout << "Invalid month or sales figure" << endl; 53 9 50 } // end function setsales 51 52 // print total annual sales (with help of utility function) salesp.cpp (3 of 3) 53 void SalesPerson::printAnnualSales() 5 { 55 cout << setprecision( 2 ) << fixed 56 << "\nthe total annual sales are: $" 57 << totalannualsales() << endl; // call utility function 5 59 } // end function printannualsales private utility function to 60 61 // private utility function to total annual sales help function 62 double SalesPerson::totalAnnualSales() 63 { printannualsales; encapsulates es logic of 6 double total = 0.0; // initialize total manipulating sales array. 65 66 for ( int i = 0; i < // summarize sales results 12; i++ ) 67 total += sales[ i ]; 6 69 return total; 70 71 } // end function totalannualsales 1 // Fig. 6.: fig06_.cpp 2 // Demonstrating a utility function. 3 // Compile this program with salesp.cpp fig06_.cpp 5 // include SalesPerson class definition from salesp.h (1 of 1) 6 #include "salesp.h" 7 int main() Simple sequence of member { 9 10 SalesPerson s; function calls; logic // create SalesPerson object s encapsulated in member 12 s.getsalesfromuser(); functions. // note simple sequential code; no 13 s.printannualsales(); // control structures in main 1 15 return 0; 16 17 } // end main 5 9

Enter sales amount for month 1: 531.76 Enter sales amount for month 2: 292.3 Enter sales amount for month 3: 59.3 Enter sales amount for month : 553.03 Enter sales amount for month 5: 376.3 Enter sales amount for month 6: 569.5 Enter sales amount for month 7: 39. Enter sales amount for month : 593.57 Enter sales amount for month 9: 909.67 Enter sales amount for month 10: 5123.5 Enter sales amount for month : 02.97 Enter sales amount for month 12: 5923.92 The total annual sales are: $60120.59 fig06_.cpp output (1 of 1) 55 6.10 Initializing Class Objects: Constructors 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, ); 56 6. Using Default Arguments with Constructors 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 57 1 // Fig. 6.12: time2.h 2 // Declaration of class Time. 3 // Member functions defined in time2.cpp. 5 // prevent multiple inclusions of header file 6 #ifndef TIME2_H 7 #define TIME2_H 9 // Time abstract data type definition Default constructor specifying 10 class Time { all arguments. 12 public: 13 Time( int = 0, int = 0, int = 0); // default constructor 1 void settime( int, int, int ); // set hour, minute, second 15 void printuniversal(); // print universal-time format 16 void printstandard(); // print standard-time format 17 1 private: 19 int hour; // 0-23 (2-hour clock format) 20 int minute; // 0-59 21 int second; // 0-59 time2.h (1 of 1) 5 23 }; // end class Time 2 25 #endif 1 // Fig. 6.13: time2.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> 5 using std::cout; 6 7 #include <iomanip> time2.cpp (1 of 3) 59 23 // set new Time value using universal time, perform validity 2 // checks on the data values and set invalid values to zero 25 void Time::setTime( int h, int m, int s ) 26 { 27 hour = ( h >= 0 && h < 2 )? h : 0; 2 minute = ( m >= 0 && m < 60 )? m : 0; 29 second = ( s >= 0 && s < 60 )? s : 0; time2.cpp (2 of 3) 60 9 using std::setfill; 10 using std::setw; 12 // include definition of class Time from time2.h 13 #include "time2.h" 1 Constructor calls settime 15 // Time constructor initializes each data member to zero; to validate passed (or default) 16 // ensures all Time objects start in a consistent state values. 17 Time::Time( int hr, int min, int sec ) 1 { 19 settime( hr, min, sec ); // validate and set time 20 21 } // end Time constructor 30 31 } // end function settime 33 // print Time in universal format 3 void Time::printUniversal() 35 { 36 cout << setfill( '0' ) << setw( 2 ) << hour << ":" 37 << setw( 2 ) << minute << ":" 3 << setw( 2 ) << second; 39 0 } // end function printuniversal 1 10

2 // print Time in standard format 3 void Time::printStandard() { 5 cout << ( ( hour == 0 hour == 12 )? 12 : hour % 12 ) 6 << ":" << setfill( '0' ) << setw( 2 ) << minute 7 << ":" << setw( 2 ) << second << ( hour < 12? " AM" : " PM" ); 9 50 } // end function printstandard time2.cpp (3 of 3) 61 1 // Fig. 6.1: fig06_1.cpp 2 // Demonstrating a default constructor for class Time. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 7 // include definition of class Time from time2.h 9 #include "time2.h" fig06_1.cpp (1 of 2) 62 10 int main() 12 { 13 Time t1; // all arguments defaulted 1 Time t2( 2 ); // minute and second defaulted 15 Time t3( 21, 3 ); // second defaulted 16 Time t( 12, 25, 2 // all values specified ); 17 Time t5( 27, 7, 99 ); // all bad values specified Initialize Time objects using default arguments. 1 19 cout << "Constructed with:\n\n" 20 << "all default arguments:\n "; 21 t1.printuniversal(); // 00:00:00 cout << "\n "; 23 t1.printstandard(); // 12:00:00 AM Initialize Time object with invalid values; validity checking will set values to 0. 2 25 cout << "\n\nhour specified; default minute and second:\n "; 26 t2.printuniversal(); // 02:00:00 27 cout << "\n "; 2 t2.printstandard(); // 2:00:00 AM 29 30 cout << "\n\nhour and minute specified; default second:\n "; 31 t3.printuniversal(); // 21:3:00 cout << "\n "; 33 t3.printstandard(); // 9:3:00 PM fig06_1.cpp (2 of 2) 63 Constructed with: all default arguments: 00:00:00 12:00:00 AM hour specified; default minute and second: 02:00:00 2:00:00 AM fig06_1.cpp output (1 of 1) 6 3 35 cout << "\n\nhour, minute, and second specified:\n "; 36 t.printuniversal(); // 12:25:2 37 cout << "\n "; 3 t.printstandard(); // 12:25:2 PM 39 t5 constructed with invalid 0 cout << "\n\nall invalid values specified:\n "; arguments; values set to 0. 1 t5.printuniversal(); // 00:00:00 2 cout << "\n "; 3 t5.printstandard(); // 12:00:00 AM cout << endl; 5 6 return 0; hour and minute specified; default second: 21:3:00 9:3:00 PM hour, minute, and second specified: 12:25:2 12:25:2 PM all invalid values specified: 00:00:00 12:00:00 AM 7 } // end main 6.12 Destructors 65 6.1 Using Set and Get Functions 66 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 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

1 // Fig. 6.1: time3.h 2 // Declaration of class Time. 3 // Member functions defined in time3.cpp 5 // prevent multiple inclusions of header file 6 #ifndef TIME3_H 7 #define TIME3_H time3.h (1 of 2) 67 25 void printuniversal(); // output universal-time format 26 void printstandard(); // output standard-time format 27 2 private: 29 int hour; // 0-23 (2-hour clock format) 30 int minute; // 0-59 31 int second; // 0-59 time3.h (2 of 2) 6 9 class Time { 33 }; // end clas Time 10 public: 12 Time( int = 0, int = 0, int = 0 ); // default constructor 13 1 // set functions 15 void settime( int, int, int ); // set hour, minute, second 16 void sethour( int ); // set hour 17 void setminute( int ); // set minute 1 void setsecond( int ); // set second 19 20 // get functions 21 int gethour(); // return hour int getminute(); // return minute 23 int getsecond(); // return second Set functions. Get functions. 3 35 #endif 2 1 // Fig. 6.19: time3.cpp 2 // Member-function definitions for Time class. 3 #include <iostream> 5 using std::cout; 6 7 #include <iomanip> 9 using std::setfill; 10 using std::setw; 12 // include definition of class Time from time3.h 13 #include "time3.h" 1 15 // constructor function to initialize private data; 16 // calls member function settime to set variables; 17 // default values are 0 (see class definition) 1 Time::Time( int hr, int min, int sec ) 19 { 20 settime( hr, min, sec ); 21 } // end Time constructor time3.cpp (1 of ) 69 2 // set hour, minute and second values 25 void Time::setTime( int h, int m, int s ) 26 { 27 sethour( h ); time3.cpp (2 of ) 2 setminute( m ); 29 setsecond( s ); 30 Call set functions to perform 31 } // end function settime validity checking. 33 // set hour value 3 void Time::setHour( int h ) 35 { 36 hour = ( h >= 0 && h < 2 )? h : 0; 37 3 } // end function sethour 39 Set functions perform validity 0 // set minute value checks before modifying data. 1 void Time::setMinute( int m ) 2 { 3 minute = ( m >= 0 && m < 60 )? m : 0; 5 } // end function setminute 70 23 6 7 // set second value void Time::setSecond( int s ) 9 { 50 second = ( s >= 0 && s < 60 )? s : 0; 51 52 } // end function setsecond 53 5 // return hour value 55 int Time::getHour() 56 { 57 return hour; 5 59 } // end function gethour 60 61 // return minute value 62 int Time::getMinute() 63 { 6 return minute; 65 66 } // end function getminute 67 Set function performs validity checks before modifying data. Get functions allow client to read data. time3.cpp (3 of ) 71 6 // return second value 69 int Time::getSecond() 70 { 71 return second; 72 73 } // end function getsecond Get function allows client to 7 read data. 75 // print Time in universal format 76 void Time::printUniversal() 77 { 7 cout << setfill( '0' ) << setw( 2 ) << hour << ":" 79 << setw( 2 ) << minute << ":" 0 << setw( 2 ) << second; 1 2 } // end function printuniversal 3 // print Time in standard format 5 void Time::printStandard() 6 { 7 cout << ( ( hour == 0 hour == 12 )? 12 : hour % 12 ) << ":" << setfill( '0' ) << setw( 2 ) << minute 9 << ":" << setw( 2 ) << second 90 << ( hour < 12? " AM" : " PM" ); time3.cpp ( of ) 72 91 92 } // end function printstandard 12

1 // Fig. 6.20: fig06_20.cpp 2 // Demonstrating the Time class set and get functions 3 #include <iostream> 5 using std::cout; 6 using std::endl; 7 // include definition of class Time from time3.h 9 #include "time3.h" 10 void incrementminutes( Time &, const int ); // prototype 12 13 int main() 1 { 15 Time t; // create Time object 16 17 // set time individual set functions using 1 t.sethour( 17 ); // set hour to valid value 19 t.setminute( 3 ); // set minute to valid value 20 t.setsecond( 25 ); // set second to valid value Invoke set functions to set valid values. fig06_20.cpp (1 of 3) 73 // use get functions to obtain hour, minute and second 23 cout << "Result of setting all valid values:\n" 2 << " Hour: " << t.gethour() Attempt to set invalid values 25 << " Minute: " << t.getminute() using set functions. fig06_20.cpp 26 << " Second: " << t.getsecond(); (2 of 3) 27 2 // set time using individual set functions 29 t.sethour( 23 ); // invalid hour set to 0 30 t.setminute( 3 ); // set minute to valid value 31 t.setsecond( 6373 ); // invalid second set to 0 Invalid values result in setting data members to 0. 33 // display hour, minute and second after setting 3 // invalid hour and second values 35 cout << "\n\nresult of attempting to set invalid hour and" 36 << " second:\n Hour: " << t.gethour() Modify data members using 37 << " Minute: " << t.getminute() function settime. 3 << " Second: " << t.getsecond() << "\n\n"; 39 0 t.settime(, 5, 0 ); // set time 1 incrementminutes( t, 3 ); // increment t's minute by 3 7 21 2 3 return 0; 5 } // end main 6 7 // add specified number of minutes to a Time object void incrementminutes( Time &tt, const int count ) 9 { 50 cout << "Incrementing minute " << count 51 << " times:\nstart time: "; 52 tt.printstandard(); 53 5 for ( int i = 0; i < count; i++ ) { 55 tt.setminute( ( tt.getminute() + 1 ) % 60 ); 56 57 if ( tt.getminute() == 0 ) 5 tt.sethour( ( tt.gethour() + 1 ) % 2); 59 60 cout << "\nminute + 1: "; 61 tt.printstandard(); fig06_20.cpp Using get functions (3 of to 3) read data and set functions to modify data. 75 Result of setting all valid values: Hour: 17 Minute: 3 Second: 25 Result of attempting to set invalid hour and second: Hour: 0 Minute: 3 Second: 0 Incrementing minute 3 times: Start time: :5:00 AM Attempting to set data minute + 1: :59:00 AM minute + 1: 12:00:00 PM members with invalid values minute + 1: 12:01:00 PM results in error message and members set to 0. fig06_20.cpp output (1 of 1) 76 62 63 } // end for 6 65 cout << endl; 66 67 } // end function incrementminutes 13