Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Similar documents
Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Classes and Objects. Again: Distance between points within the first quadrant. José Valente de Oliveira 4-1

Overview. Chapter 18 Vectors and Arrays. Reminder. vector. Bjarne Stroustrup

Chapter 2. C++ Basics. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

n The C++ template facility provides the ability to define n A generic facility allows code to be written once then

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

From last week. Lecture 5. Outline. Principles of programming languages

CS 11 C track: lecture 1

CMPT 125 Assignment 2 Solutions

. Written in factored form it is easy to see that the roots are 2, 2, i,

Chapter 3. More Flow of Control. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

The Magma Database file formats

! Given the following Structure: ! We can define a pointer to a structure. ! Now studentptr points to the s1 structure.

Examples and Applications of Binary Search

Python Programming: An Introduction to Computer Science

Ones Assignment Method for Solving Traveling Salesman Problem

Chapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Computers and Scientific Thinking

COP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen

Recursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:

condition w i B i S maximum u i

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Basic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000.

Lecture 1: Introduction and Strassen s Algorithm

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:

Lecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance

11.2. Overloading Operators

Hash Tables. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015.

CS211 Fall 2003 Prelim 2 Solutions and Grading Guide

6.854J / J Advanced Algorithms Fall 2008

WORKED EXAMPLE 7.1. Producing a Mass Mailing. We want to automate the process of producing mass mailings. A typical letter might look as follows:

CSC 220: Computer Organization Unit 11 Basic Computer Organization and Design

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Last Class. Announcements. Lecture Outline. Types. Structural Equivalence. Type Equivalence. Read: Scott, Chapters 7 and 8. T2 y; x = y; n Types

Analysis of Algorithms

Algorithm. Counting Sort Analysis of Algorithms

Threads and Concurrency in Java: Part 1

CS : Programming for Non-Majors, Summer 2007 Programming Project #3: Two Little Calculations Due by 12:00pm (noon) Wednesday June

Outline and Reading. Analysis of Algorithms. Running Time. Experimental Studies. Limitations of Experiments. Theoretical Analysis

Threads and Concurrency in Java: Part 1

What are we going to learn? CSC Data Structures Analysis of Algorithms. Overview. Algorithm, and Inputs

Lecture 5. Counting Sort / Radix Sort

Lecturers: Sanjam Garg and Prasad Raghavendra Feb 21, Midterm 1 Solutions

Recursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames

The isoperimetric problem on the hypercube

Polynomial Functions and Models. Learning Objectives. Polynomials. P (x) = a n x n + a n 1 x n a 1 x + a 0, a n 0

Python Programming: An Introduction to Computer Science

Elementary Educational Computer

COSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1

n Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis

APPLICATION NOTE PACE1750AE BUILT-IN FUNCTIONS

Computer Science Foundation Exam. August 12, Computer Science. Section 1A. No Calculators! KEY. Solutions and Grading Criteria.

10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output

Running Time. Analysis of Algorithms. Experimental Studies. Limitations of Experiments

EE123 Digital Signal Processing

Running Time ( 3.1) Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Analysis of Algorithms

9.1. Sequences and Series. Sequences. What you should learn. Why you should learn it. Definition of Sequence

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

n Maurice Wilkes, 1949 n Organize software to minimize errors. n Eliminate most of the errors we made anyway.

Data Structures and Algorithms. Analysis of Algorithms

Pattern Recognition Systems Lab 1 Least Mean Squares

The Implementation of Data Structures in Version 5 of Icon* Ralph E. Gr is wo Id TR 85-8

DATA STRUCTURES. amortized analysis binomial heaps Fibonacci heaps union-find. Data structures. Appetizer. Appetizer

Exercise 6 (Week 42) For the foreign students only.

Analysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis

top() Applications of Stacks

Linked Lists 11/16/18. Preliminaries. Java References. Objects and references. Self references. Linking self-referential nodes

Last class. n Scheme. n Equality testing. n eq? vs. equal? n Higher-order functions. n map, foldr, foldl. n Tail recursion

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)

Guide to Applying Online

Homework 1 Solutions MA 522 Fall 2017

Analysis of Algorithms

Morgan Kaufmann Publishers 26 February, COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 5

IMP: Superposer Integrated Morphometrics Package Superposition Tool

UNIT 4C Iteration: Scalability & Big O. Efficiency

CIS 121. Introduction to Trees

How do we evaluate algorithms?

Term Project Report. This component works to detect gesture from the patient as a sign of emergency message and send it to the emergency manager.

Message Integrity and Hash Functions. TELE3119: Week4

CMSC Computer Architecture Lecture 3: ISA and Introduction to Microarchitecture. Prof. Yanjing Li University of Chicago

One advantage that SONAR has over any other music-sequencing product I ve worked

implement language system

Sorting 9/15/2009. Sorting Problem. Insertion Sort: Soundness. Insertion Sort. Insertion Sort: Running Time. Insertion Sort: Soundness

EE University of Minnesota. Midterm Exam #1. Prof. Matthew O'Keefe TA: Eric Seppanen. Department of Electrical and Computer Engineering

Parabolic Path to a Best Best-Fit Line:

ENGI 4421 Probability and Statistics Faculty of Engineering and Applied Science Problem Set 1 Descriptive Statistics

The number n of subintervals times the length h of subintervals gives length of interval (b-a).

Oracle Server. What s New in this Release? Release Notes

Module 8-7: Pascal s Triangle and the Binomial Theorem

Behavioral Modeling in Verilog

CS200: Hash Tables. Prichard Ch CS200 - Hash Tables 1

Sub-Exponential Algorithms for 0/1 Knapsack and Bin Packing

Transcription:

Chapter 11 Frieds, Overloaded Operators, ad Arrays i Classes Copyright 2014 Pearso Addiso-Wesley. All rights reserved.

Overview 11.1 Fried Fuctios 11.2 Overloadig Operators 11.3 Arrays ad Classes 11.4 Classes ad Dyamic Arrays Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-3

11.1 Fried Fuctios Copyright 2014 Pearso Addiso-Wesley. All rights reserved.

Fried Fuctio Class operatios are typically implemeted as member fuctios Some operatios are better implemeted as ordiary (omember) fuctios Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-5

Program Example: A Equality Fuctio The DayOfYear class from Chapter 10 ca be ehaced to iclude a equality fuctio A equality fuctio tests two objects of type DayOfYear to see if their values represet the same date Two dates are equal if they represet the same day ad moth Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-6

Declaratio of The equality Fuctio We wat the equality fuctio to retur a value of type bool that is true if the dates are the same The equality fuctio requires a parameter for each of the two dates to compare The declaratio is bool equal(dayofyear date1, DayOfYear date2); Notice that equal is ot a member of the class DayOfYear Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-7

Defiig Fuctio equal The fuctio equal, is ot a member fuctio It must use public accessor fuctios to obtai the day ad moth from a DayOfYear object equal ca be defied i this way: bool equal(dayofyear date1, DayOfYear date2) { retur ( date1.get_moth( ) == date2.get_moth( ) && date1.get_day( ) == date2.get_day( ) ); } Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-8

Usig The Fuctio equal The equal fuctio ca be used to compare dates i this maer if ( equal( today, bach_birthday) ) cout << "It's Bach's birthday!"; A complete program usig fuctio equal is foud i Display 11.1 (1) Display 11.1 (2) Display 11.1 (3) Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-9

Is equal Efficiet? Fuctio equal could be made more efficiet Equal uses member fuctio calls to obtai the private data values Direct access of the member variables would be more efficiet (faster) Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-10

A More Efficiet equal As defied here, equal is more efficiet, but ot legal bool equal(dayofyear date1, DayOfYear date2) { retur (date1.moth = = date2.moth && date1.day = = date2.day ); } The code is simpler ad more efficiet Direct access of private member variables is ot legal! Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-11

Fried Fuctios Fried fuctios are ot members of a class, but ca access private member variables of the class A fried fuctio is declared usig the keyword fried i the class defiitio A fried fuctio is ot a member fuctio A fried fuctio is a ordiary fuctio A fried fuctio has extraordiary access to data members of the class As a fried fuctio, the more efficiet versio of equal is legal Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-12

Declarig A Fried The fuctio equal is declared a fried i the abbreviated class defiitio here class DayOfYear { public: fried bool equal(dayofyear date1, DayOfYear date2); // The rest of the public members private: // the private members }; Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-13

Usig A Fried Fuctio A fried fuctio is declared as a fried i the class defiitio A fried fuctio is defied as a omember fuctio without usig the "::" operator A fried fuctio is called without usig the '.' operator Display 11.2 Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-14

Fried Declaratio Sytax The sytax for declarig fried fuctio is class class_ame { public: fried Declaratio_for_Fried_Fuctio_1 fried Declaratio_for_Fried_Fuctio_2 Member_Fuctio_Declaratios private: Private_Member_Declaratios }; Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-15

Are Frieds Needed? Fried fuctios ca be writte as o-fried fuctios usig the ormal accessor ad mutator fuctios that should be part of the class The code of a fried fuctio is simpler ad it is more efficiet Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-16

Choosig Frieds How do you kow whe a fuctio should be a fried or a member fuctio? I geeral, use a member fuctio if the task performed by the fuctio ivolves oly oe object I geeral, use a omember fuctio if the task performed by the fuctio ivolves more tha oe object Choosig to make the omember fuctio a fried is a decisio of efficiecy ad persoal taste Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-17

Program Example: The Moey Class (versio 1) Display 11.3 demostrates a class called Moey U.S. currecy is represeted Value is implemeted as a iteger represetig the value as if coverted to peies A iteger allows exact represetatio of the value Type log is used to allow larger values Two fried fuctios, equal ad add, are used Display 11.3 (1 5) Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-18

Characters to Itegers Notice how fuctio iput (Display 11.3) processes the dollar values etered First read the character that is a $ or a If it is the -, set the value of egative to true ad read the $ sig which should be ext Next read the dollar amout as a log Next read the decimal poit ad cets as three characters digit_to_it is the used to covert the cets characters to itegers Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-19

digit_to_it (optioal) digit_to_it is defied as it digit_to_it(char c) { retur ( it ( c ) it ( '0') ); } A digit, such as '3' is parameter c This is the character '3' ot the umber 3 The type cast it(c) returs the umber that implemets the character stored i c The type cast it('0') returs the umber that implemets the character '0' Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-20

it( c) it ('0')? The umbers implemetig the digits are i i order it('0') + 1 is equivalet to it('1') it('1') + 1 is equivalet to it('2') If c is '0' it( c ) - it('0') returs iteger 0 If c is '1' it( c ) it ('0') returs iteger 1 Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-21

Leadig Zeros Some compilers iterpret a umber with a leadig zero as a base 8 umber Base 8 uses digits 0 7 Usig 09 to represet 9 cets could cause a error the digit 9 is ot allowed i a base 8 umber The ANSI C++ stadard is that iput should be iterpreted as base 10 regardless of a leadig zero Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-22

Parameter Passig Efficiecy A call-by-value parameter less efficiet tha a call-by-referece parameter The parameter is a local variable iitialized to the value of the argumet This results i two copies of the argumet A call-by-referece parameter is more efficiet The parameter is a placeholder replaced by the argumet There is oly oe copy of the argumet Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-23

Class Parameters It ca be much more efficiet to use call-by-referece parameters whe the parameter is of a class type Whe usig a call-by-referece parameter If the fuctio does ot chage the value of the parameter, mark the parameter so the compiler kows it should ot be chaged Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-24

cost Parameter Modifier To mark a call-by-referece parameter so it caot be chaged: Use the modifier cost before the parameter type The parameter becomes a costat parameter cost used i the fuctio declaratio ad defiitio Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-25

cost Parameter Example Example (from the Moey class of Display 11.3): A fuctio declaratio with costat parameters fried Moey add(cost Moey& amout1, cost Moey& amout2); A fuctio defiitio with costat parameters Moey add(cost Moey& amout1, cost Moey& amout2) { } Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-26

cost Cosideratios Whe a fuctio has a costat parameter, the compiler will make certai the parameter caot be chaged by the fuctio What if the parameter calls a member fuctio? Moey add(cost Moey& amout1, cost Moey& amout2) { amout1.iput( ci ); } The call to iput will chage the value of amout1! Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-27

cost Ad Accessor Fuctios Will the compiler accept a accessor fuctio call from the costat parameter? Moey add(cost Moey& amout1, cost Moey& amout2) { amout1.output(cout); } The compiler will ot accept this code There is o guaratee that output will ot chage the value of the parameter Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-28

cost Modifies Fuctios If a costat parameter makes a member fuctio call The member fuctio called must be marked so the compiler kows it will ot chage the parameter cost is used to mark fuctios that will ot chage the value of a object cost is used i the fuctio declaratio ad the fuctio defiitio Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-29

Fuctio Declaratios With cost To declare a fuctio that will ot chage the value of ay member variables: Use cost after the parameter list ad just before the semicolo class Moey { public: void output (ostream& outs) cost ; Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-30

Fuctio Defiitios With cost To defie a fuctio that will ot chage the value of ay member variables: Use cost i the same locatio as the fuctio declaratio void Moey::output(ostream& outs) cost { // output statemets } Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-31

cost Problem Solved Now that output is declared ad defied usig the cost modifier, the compiler will accept this code Moey add(cost Moey& amout1, cost Moey& amout2) { amout1.output(cout); } Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-32

cost Wrapup Usig cost to modify parameters of class types improves program efficiecy cost is typed i frot of the parameter's type Member fuctios called by costat parameters must also use cost to let the compiler kow they do ot chage the value of the parameter cost is typed followig the parameter list i the declaratio ad defiitio Display 11.4 Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-33

Use cost Cosistetly Oce a parameter is modified by usig cost to make it a costat parameter Ay member fuctios that are called by the parameter must also be modified usig cost to tell the compiler they will ot chage the parameter It is a good idea to modify, with cost, every member fuctio that does ot chage a member variable Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-34

Sectio 11.1 Coclusio Ca you Describe the promise that you make to the compiler whe you modify a parameter with cost? Explai why this declaratio is probably ot correct? class Moey { public: void iput(istream& is) cost; }; Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-35

11.2 Overloadig Operators Copyright 2014 Pearso Addiso-Wesley. All rights reserved.

Overloadig Operators I the Moey class, fuctio add was used to add two objects of type Moey I this sectio we see how to use the '+' operator to make this code legal: Moey total, cost, tax; total = cost + tax; // istead of total = add(cost, tax); Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-37

Operators As Fuctios A operator is a fuctio used differetly tha a ordiary fuctio A ordiary fuctio call eclosed its argumets i parethesis add(cost, tax) With a biary operator, the argumets are o either side of the operator cost + tax Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-38

Operator Overloadig Operators ca be overloaded The defiitio of operator + for the Moey class is early the same as member fuctio add To overload the + operator for the Moey class Use the ame + i place of the ame add Use keyword operator i frot of the + Example: fried Moey operator + (cost Moey& amout1 Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-39

Operator Overloadig Rules At least oe argumet of a overloaded operator must be of a class type A overloaded operator ca be a fried of a class New operators caot be created The umber of argumets for a operator caot be chaged The precedece of a operator caot be chaged., ::, *, ad? caot be overloaded Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-40

Program Example: Overloadig Operators The Moey class with overloaded operators + ad == is demostrated i Display 11.5 (1) Display 11.5 (2) Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-41

Display 11.5 (1/2) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-42

Display 11.5 (2/2) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-43

Automatic Type Coversio With the right costructors, the system ca do type coversios for your classes This code (from Display 11.5) actually works Moey base_amout(100, 60), full_amout; full_amout = base_amout + 25; The iteger 25 is coverted to type Moey so it ca be added to base_amout! How does that happe? Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-44

Type Coversio Evet 1 Whe the compiler sees base_amout + 25, it first looks for a overloaded + operator to perform Moey_object + iteger If it exists, it might look like this fried Moey operator +(cost Moey& amout1, cost it& amout2); Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-45

Type Coversio Evet 2 Whe the appropriate versio of + is ot foud, the compiler looks for a costructor that takes a sigle iteger The Moey costructor that takes a sigle parameter of type log will work The costructor Moey(log dollars) coverts 25 to a Moey object so the two values ca be added! Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-46

Type Coversio Agai Although the compiler was able to fid a way to add base_amout + 25 this additio will cause a error base_amout + 25.67 There is o costructor i the Moey class that takes a sigle argumet of type double Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-47

A Costructor For double To permit base_amout + 25.67, the followig costructor should be declared ad defied class Moey { public: Moey(double amout); // Iitialize object so its value is $amout Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-48

Overloadig Uary Operators Uary operators take a sigle argumet The uary operator is used to egate a value x = -y ++ ad - - are also uary operators Uary operators ca be overloaded The Moey class of Display 11.6 ca icludes A biary operator A uary operator Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-49

Overloadig - Overloadig the operator with two parameters allows us to subtract Moey objects as i Moey amout1, amout2, amout2; amout3 = amout1 amout2; Overloadig the operator with oe parameter allows us to egate a moey value like this amout3 = -amout1; Display 11.6 Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-50

Display 11.6 Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-51

Overloadig << ad >> The isertio operator << is a biary operator The first operad is the output stream The secod operad is the value followig << cout << "Hello out there.\"; Operad 1 Operad 2 Operator Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-52

Replacig Fuctio output Overloadig the << operator allows us to use << istead of Moey's output fuctio Give the declaratio: Moey amout(100); amout.output( cout ); ca become cout << amout; Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-53

What Does << Retur? Because << is a biary operator cout << "I have " << amout << " i my purse."; seems as if it could be grouped as ( (cout << "I have" ) << amout) << "i my purse."; To provide cout as a argumet for << amout, (cout << "I have") must retur cout Display 11.7 Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-54

Display 11.7 Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-55

Overloaded << Declaratio Based o the previous example, << should retur its first argumet, the output stream This leads to a declaratio of the overloaded << operator for the Moey class: class Moey { public: fried ostream& operator << (ostream& outs, cost Moey& amout); Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-56

Overloaded << Defiitio The followig defies the << operator ostream& operator <<(ostream& outs, cost Moey& amout) { <Same as the body of Moey::output i Display 11.3 (except all_cets is replaced with amout.all_cets) > } retur outs; Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-57

Retur ostream&? The & meas a referece is retured So far all our fuctios have retured values The value of a stream object is ot so simple to retur The value of a stream might be a etire file, the keyboard, or the scree! We wat to retur the stream itself, ot the value of the stream The & meas that we wat to retur the stream, ot its value Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-58

Overloadig >> Overloadig the >> operator for iput is very similar to overloadig the << for output >> could be defied this way for the Moey class istream& operator >>(istream& is, Moey& amout); { } <This part is the same as the body of Moey::iput i Display 11.3 (except that all_cets is replaced with amout.all_cets)> retur is; Display 11.8 (1-4) Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-59

Display 11.8 (1/4) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-60

Display 11.8(2/4) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-61

Display 11.8 (3/4) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-62

Display 11.8 (4/4) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-63

Sectio 11.2 Coclusio Ca you Describe the purpose of a makig a fuctio a fried? Describe the use of costat parameters? Idetify the retur type of the overloaded operators << ad >>? Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-64

11.3 Arrays ad Classes Copyright 2014 Pearso Addiso-Wesley. All rights reserved.

Arrays ad Classes Arrays ca use structures or classes as their base types Example: struct WidIfo { double velocity; char directio; } WidIfo data_poit[10]; Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-66

Accessig Members Whe a array's base type is a structure or a class Use the dot operator to access the members of aidexed variable Example: for (i = 0; i < 10; i++) { cout << "Eter velocity: "; ci >> data_poit[i].velocity; } Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-67

A Array of Moey The Moey class of Chapter 11 ca be the base type for a array Whe a array of classes is declared The default costructor is called to iitialize the idexed variables A array of class Moey is demostrated i Display 11.9 (1-3) Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-68

Arrays as Structure Members A structure ca cotai a array as a member Example: struct Data { double time[10]; it distace; } Data my_best; my_best cotais a array of type double Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-69

Accessig Array Elemets To access the array elemets withi a structure Use the dot operator to idetify the array withi the structure Use the [ ]'s to idetify the idexed variable desired Example: my_best.time[i] refereces the ith idexed variable of the variable time i the structure my_best Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-70

Arrays as Class Members Class TemperatureList icludes a array The array, amed list, cotais temperatures Member variable size is the umber of items stored class TemperatureList { public: TemperatureList( ); //Member fuctios private: double list [MAX_LIST_SIZE]; it size; } Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-71

Overview of TemperatureList To create a object of type TemperatureList: TemperatureList my_data; To add a temperature to the list: My_data.add_temperature(77); A check is made to see if the array is full << is overloaded so output of the list is cout << my_data; Display 11.10 (1-2) Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-72

Sectio 11.3 Coclusio Ca you Declare a array as a member of a class? Declare a array of objects of a class? Write code to call a member fuctio of a elemet i a array of objects of a class? Write code to access a elemet of a array of itegers that is a member of a class? Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-73

11.4 Classes ad Dyamic Arrays Copyright 2014 Pearso Addiso-Wesley. All rights reserved.

Classes ad Dyamic Arrays A dyamic array ca have a class as its base type A class ca have a member variable that is a dyamic array I this sectio you will see a class usig a dyamic array as a member variable. Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-75

Program Example: A Strig Variable Class We will defie the class StrigVar StrigVar objects will be strig variables StrigVar objects use dyamic arrays whose size is determied whe the program is ruig The StrigVar class is similar to the strig class discussed earlier Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-76

The StrigVar Costructors The default StrigVar costructor creates a object with a maximum strig legth of 100 Aother StrigVar costructor takes a argumet of type it which determies the maximum strig legth of the object A third StrigVar costructor takes a C-strig argumet ad sets maximum legth to the legth of the C-strig copies the C-strig ito the object's strig value Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-77

The StrigVar Iterface I additio to costructors, the StrigVar iterface icludes: Member fuctios it legth( ); void iput_lie(istream& is); fried ostream& operator << (ostream& outs, cost StrigVar& the_strig); Copy Costructor discussed later Destructor discussed later Display 11.11 (1) Display 11.11 (2) Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-78

A StrigVar Sample Program Usig the StrigVar iterface of Display 11.11, we ca write a program usig the StrigVar class The program uses fuctio coversatio to Create two StrigVar objects, your_ame ad our_ame your_ame ca cotai ay strig max_ame_size or shorter i legth our_ame is iitialized to "Borg" ad ca have ay strig of 4 or less characters Display 11.11 (3) Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-79

The StrigVar Implemetatio StrigVar uses a dyamic array to store its strig StrigVar costructors call ew to create the dyamic array for member variable value '\0' is used to termiate the strig The size of the array is ot determied util the array is declared Costructor argumets determie the size Display 11.12 (1) Display 11.12 (2) Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-80

Dyamic Variables Dyamic variables do ot "go away" uless delete is called Eve if a local poiter variable goes away at the ed of a fuctio, the dyamic variable it poited to remais uless delete is called A user of the SrigVar class could ot kow that a dyamic array is a member of the class, so could ot be expected to call delete whe fiished with a StrigVar object Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-81

Destructors A destructor is a member fuctio that is called automatically whe a object of the class goes out of scope The destructor cotais code to delete all dyamic variables created by the object A class has oly oe destructor with o argumets The ame of the destructor is distiguished from the default costructor by the tilde symbol ~ Example: ~StrigVar( ); Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-82

~StrigVar The destructor i the StrigVar class must call delete [ ] to retur the memory of ay dyamic variables to the freestore Example: StrigVar::~StrigVar( ) { delete [ ] value; } Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-83

Poiters as Call-by-Value Parameters Usig poiters as call-by-value parameters yields results you might ot expect Remember that parameters are local variables No chage to the parameter should cause a chage to the argumet The value of the parameter is set to the value of the argumet (a address is stored i a poiter variable) The argumet ad the parameter hold the same address If the parameter is used to chage the value poited to, this is the same value poited to by the argumet! Display 11.13 Display 11.14 Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-84

Copy Costructors The problem with usig call-by-value parameters with poiter variables is solved by the copy costructor. A copy costructor is a costructor with oe parameter of the same type as the class The parameter is a call-by-referece parameter The parameter is usually a costat parameter The costructor creates a complete, idepedet copy of its argumet Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-85

StrigVar Copy Costructor This code for the StrigVar copy costructor Creates a ew dyamic array for a copy of the argumet Makig a ew copy, protects the origial from chages StrigVar::StrigVar(cost StrigVar& strig_object) : max_legth(strig_object.legth()) { value = ew char[max_legth+ 1]; strcpy(value, strig_object.value); } Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-86

Callig a Copy Costructor A copy costructor ca be called as ay other costructor whe declarig a object The copy costructor is called automatically Whe a class object is defied ad iitialized by a object of the same class Whe a fuctio returs a value of the class type Whe a argumet of the class type is plugged i for a call-by-value parameter Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-87

The Need For a Copy Costructor This code (assumig o copy costructor) illustrates the eed for a copy costructor void show_strig(strigvar the_strig) { } StrigVar greetig("hello"); show_strig(greetig); cout << greetig << edl; Whe fuctio show_strig is called, greetig is copied ito the_strig the_strig.value is set equal to greetig.value Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-88

The Need For a Copy Costructor (cot.) Sice greetig.value ad the_strig.value are poiters, they ow poit to the same dyamic array "Hello" greetig.value the_strig.value Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-89

The Need For a Copy Costructor (cot.) Whe show_strig eds, the destructor for the_strig executes, returig the dyamic array poited to by the_strig.value to the freestore Udefied greetig.value the_strig.value greetig.value ow poits to memory that has bee give back to the freestore! Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-90

The Need For a Copy Costructor (cot.) Two problems ow exist for object greetig Attemptig to output greetig.value is likely to produce a error I some istaces all could go OK Whe greetig goes out of scope, its destructor will be called Callig a destructor for the same locatio twice is likely to produce a system crashig error Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-91

Copy Costructor Demostratio Usig the same example, but with a copy costructor defied greetig.value ad the_strig.value poit to differet locatios i memory "Hello" "Hello" greetig.value the_strig.value Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-92

Copy Costructor Demostratio (cot.) Whe the_strig goes out of scope, the destructor is called, returig the_strig.value to the freestore "Hello" udefied greetig.value the_strig.value greetig.value still exists ad ca be accessed or deleted without problems Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-93

Whe To Iclude a Copy Costructor Whe a class defiitio ivolves poiters ad dyamically allocated memory usig "ew", iclude a copy costructor Classes that do ot ivolve poiters ad dyamically allocated memory do ot eed copy costructors Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-94

The Big Three The big three iclude The copy costructor The assigmet operator The destructor If you eed to defie oe, you eed to defie all Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-95

The Assigmet Operator Give these declaratios: StrigVar strig(10), strig2(20); the statemet strig1 = strig2; is legal But, sice StrigVar's member value is a poiter, we have strig1.value ad strig2.value poitig to the same memory locatio Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-96

Overloadig = The solutio is to overload the assigmet operator = so it works for StrigVar operator = is overloaded as a member fuctio Example: operator = declaratio void operator=(cost StrigVar& right_side); Right_side is the argumet from the right side of the = operator Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-97

Defiitio of = The defiitio of = for StrigVar could be: void StrigVar::operator= (cost StrigVar& right_side) { it ew_legth = strle(right_side.value); if (( ew_legth) > max_legth) ew_legth = max_legth; for(it i = 0; i < ew_legth; i++) value[i] = right_side.value[i]; } value[ew_legth] = '\0'; Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-98

= Details This versio of = for StrigVar Compares the legths of the two StrigVar's Uses oly as may characters as fit i the left had StrigVar object Makes a idepedet copy of the right had object i the left had object Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-99

Problems with = The defiitio of operator = has a problem Usually we wat a copy of the right had argumet regardless of its size To do this, we eed to delete the dyamic array i the left had argumet ad allocate a ew array large eough for the right had side's dyamic array The ext slide shows this (buggy) attempt at overloadig the assigmet operator Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-100

Aother Attempt at = void StrigVar::operator= (cost StrigVar& right_side) { delete [ ] value; it ew_legth = strle(right_side.value); max_legth = ew_legth; value = ew char[max_legth + 1]; for(it i = 0; i < ew_legth; i++) value[i] = right_side.value[i]; } value[ew_legth] = '\0'; Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-101

A New Problem With = The ew defiitio of operator = has a problem What happes if we happe to have the same object o each side of the assigmet operator? my_strig = my_strig; This versio of operator = first deletes the dyamic array i the left had argumet. Sice the objects are the same object, there is o loger a array to copy from the right had side! Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-102

A Better = Operator void StrigVar::operator = (cost StrigVar& right_side) { it ew_legth = strle(right_side.value); if (ew_legth > max_legth) //delete value oly { // if more space delete [ ] value; // is eeded max_legth = ew_legth; value = ew char[max_legth + 1]; } } for (it I = 0; i< ew_legth; i++) value[i] = right_side.value[i]; value[ew_legth] = '\0'; Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-103

Sectio 11.4 Coclusio Ca you Explai why a overloaded assigmet operator is ot eeded whe the oly data cosist of built-i types? Explai what a destructor does? Explai whe a copy costructor is called? Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-104

Chapter 11 -- Ed Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-105

Display 11.1 (1/3) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-106

Display 11.1 (2/3) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-107

Display 11.1 (3/3) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-108

Display 11.2 Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-109

Display 11.3 (1/5) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-110

Display 11.3 (2/5) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-111

Display 11.3 (3/5) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-112

Display 11.3 (4/5) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-113

Display 11.3 (5/5) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-114

Display 11.4 Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-115

Display 11.9 (1/3) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-116

Display 11.9 (2/3) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-117

Display 11.9 (3/3) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-118

Display 11.10 (1/2) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-119

Display 11.10 (2/2) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-120

Display 11.11 (1/3) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-121

Display 11.11 (2/3) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-122

Display 11.11 (3/3) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-123

Display 11.12 (1/2) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-124

Display 11.12 (2/2) Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-125

Display 11.13 Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-126

Display 11.14 Back Next Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Slide 11-127