c++ programming - · pdf fileadvanced c++ programming styles and idioms. addison-wesley,...

86
C++ Programming Student Workbook

Upload: vantuyen

Post on 29-Mar-2018

223 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

C++ Programming

Student Workbook

Page 2: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

ii C++ Programming

© 1995-2002 by itcourseware, LLC 6/02B

C++ Programming

Published by itcourseware, LLC, 7245 South Havana Street, Suite 100, Englewood, CO80112

Contributing Authors: Andrew Boardman, Todd Gibson, Evans Nash

Editor: Danielle Waleri

Assistant Editor: Jan Waleri

Special thanks to: Many instructors whose ideas and careful review have contributed to thequality of this workbook, including Brandon Caldwell, Rick Sussenbach, and Lynwood Wilson,and to the many students who have offered comments, suggestions, criticisms, and insights.

Copyright © 1995-2002 by itcourseware, LLC. All rights reserved. No part of this book maybe reproduced or utilized in any form or by any means, electronic or mechanical, includingphotocopying, recording, or by an information storage retrieval system, without permission inwriting from the publisher. Inquiries should be addressed to itcourseware, LLC, 7245 SouthHavana Street, Suite 100, Englewood, CO, 80112. (303) 302-5280.

All brand names, product names, trademarks, and registered trademarks are the property oftheir respective owners.

Page 3: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Table of Contents iii

© 1995-2002 by itcourseware, LLC 6/02B

Contents

Chapter 1 - Course Introduction ............................................................................................. 9

Course Objectives ......................................................................................................... 11Course Overview ........................................................................................................... 13Suggested References (contd.) ..................................................................................... 14Suggested References .................................................................................................. 15

Chapter 2 - Classes ............................................................................................................ 17

Chapter Objectives ........................................................................................................ 19Creating a Data Structure .............................................................................................. 21Methods ........................................................................................................................ 23Object Scope................................................................................................................. 25C++ Input and Output ..................................................................................................... 27Namespaces ................................................................................................................. 29Data Abstraction ............................................................................................................ 31Enforcing Data Encapsulation........................................................................................ 33File Organization ........................................................................................................... 35Classes in C++ .............................................................................................................. 37Objects .......................................................................................................................... 39this Pointer .................................................................................................................... 41Labs .............................................................................................................................. 43

Chapter 3 - Constructors and Destructors............................................................................ 45

Chapter Objectives ........................................................................................................ 47Debug Output ................................................................................................................ 49The Default Constructor ................................................................................................. 51When are Constructors Called? ..................................................................................... 53The Destructor ............................................................................................................... 55The Copy Constructor .................................................................................................... 57Other Constructors......................................................................................................... 59Why Did It Work Before?................................................................................................ 61Composition .................................................................................................................. 63The Report Class ........................................................................................................... 65Code Reuse .................................................................................................................. 67Initialization Lists............................................................................................................ 69Labs .............................................................................................................................. 71

Page 4: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

iv C++ Programming

© 1995-2002 by itcourseware, LLC 6/02B

Chapter 4 - Inheritance ........................................................................................................ 73

Chapter Objectives ........................................................................................................ 75Inheritance ..................................................................................................................... 77Bugreport ...................................................................................................................... 79Protected Access Modifier............................................................................................. 81Access and Inheritance .................................................................................................. 83Constructors and Inheritance.......................................................................................... 85Initialization Lists Revisited ............................................................................................ 87Multiple Inheritance ........................................................................................................ 89Labs .............................................................................................................................. 91

Chapter 5 - Virtual Functions ............................................................................................... 97

Chapter Objectives ........................................................................................................ 99Inheritance and Assignment ......................................................................................... 101Inside Report's Assignment Operator ........................................................................... 103Using Pointers - A Quick Look at Basics ...................................................................... 105Class Assignment and Pointers ................................................................................... 107Class Assignment and Pointers - A Picture .................................................................. 109Static Binding ...............................................................................................................111Dynamic Binding ......................................................................................................... 113Polymorphism .............................................................................................................. 115The show_rep() Function.............................................................................................. 117Using the show_rep() Function ..................................................................................... 119Designing Member Function Inheritance ...................................................................... 121Labs ............................................................................................................................ 123

Chapter 6 - Pure Virtual Functions ..................................................................................... 125

Chapter Objectives ...................................................................................................... 127Bugfix and Its Relationship with Bugreport.................................................................... 129Bugfix: Association with Bugreport .............................................................................. 131Using Bugfix with show_rep() ....................................................................................... 133Adding Bugfix to the Hierarchy ..................................................................................... 135Coding for the Document Class ................................................................................... 137Reexamining the Document Class ............................................................................... 139Pure Virtual Functions .................................................................................................. 141Updated: Designing Member Function Inheritance ....................................................... 143Labs ............................................................................................................................ 145

Page 5: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Table of Contents v

© 1995-2002 by itcourseware, LLC 6/02B

Chapter 7 - References and Constants.............................................................................. 147

Chapter Objectives ...................................................................................................... 149References .................................................................................................................. 151Displaying References................................................................................................. 153Changing References .................................................................................................. 155Pass by Reference ...................................................................................................... 157Returning by Reference................................................................................................ 159Constant Variables ...................................................................................................... 161Constant References ................................................................................................... 163Constant Methods........................................................................................................ 165Labs ............................................................................................................................ 167

Chapter 8 - new and delete ............................................................................................... 169

Chapter Objectives ...................................................................................................... 171new and delete ............................................................................................................ 173Array Allocation ............................................................................................................ 175The Report Class ......................................................................................................... 177Compiler Version of the Copy Constructor ................................................................... 179Guidelines for Copy Constructors................................................................................. 181The Report Constructors and new ................................................................................ 183The Report Destructor and delete ................................................................................ 185Virtual Destructors ....................................................................................................... 187Labs ............................................................................................................................ 189

Chapter 9 - Casting in C++................................................................................................ 191

Chapter Objectives ...................................................................................................... 193Casting: A Review....................................................................................................... 195New Casting Syntax ..................................................................................................... 197Creating a String Class ................................................................................................ 199The String Class .......................................................................................................... 201The Conversion Constructor......................................................................................... 203Expanding Our Casting Options ................................................................................... 205Casting Operator ......................................................................................................... 207Using the Casting Operator.......................................................................................... 209Labs ............................................................................................................................ 211

Page 6: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

vi C++ Programming

© 1995-2002 by itcourseware, LLC 6/02B

Chapter 10 - Class Methods and Data .............................................................................. 213

Chapter Objectives ...................................................................................................... 215Class Data .................................................................................................................. 217Class Methods............................................................................................................. 219Using the New Data ..................................................................................................... 221More on Class Methods ............................................................................................... 223Labs ............................................................................................................................ 225

Chapter 11 - Overloaded Functions ................................................................................... 227

Chapter Objectives ...................................................................................................... 229Function Overloading ................................................................................................... 231Using Overloaded Functions ........................................................................................ 233Rules for Overloading .................................................................................................. 235Overloading Based on Constness................................................................................ 237Default Arguments ....................................................................................................... 239Invoking Functions with Default Arguments ................................................................... 241Labs ............................................................................................................................ 243

Chapter 12 - Overloaded Operators .................................................................................. 245

Chapter Objectives ...................................................................................................... 247The Basics of Overloading ........................................................................................... 249Overloading operator+ ................................................................................................. 251Coping with Commutativity........................................................................................... 253Non-Commutative Operators ....................................................................................... 255friends and Their Problems .......................................................................................... 257The Assignment Operator ............................................................................................ 259Overloading the << Operator........................................................................................ 261Using Date with cout .................................................................................................... 263Labs ............................................................................................................................ 265

Chapter 13 - Exception Handling ....................................................................................... 267

Chapter Objectives ...................................................................................................... 269Why Exception Handling? ............................................................................................ 271try / catch / throw .......................................................................................................... 273Exception Classes....................................................................................................... 275Standard Exception Hierarchy ...................................................................................... 277Multiple catch Blocks ................................................................................................... 279Catching Everything ..................................................................................................... 281

Page 7: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Table of Contents vii

© 1995-2002 by itcourseware, LLC 6/02B

Unhandled Exceptions ................................................................................................. 283Exception in Constructors and Destructors ................................................................... 285Designing for Exceptions ............................................................................................. 287Labs ............................................................................................................................ 289

Chapter 14 - Standard Template Library ............................................................................ 291

Chapter Objectives ...................................................................................................... 293Class Template Concepts ............................................................................................ 295Standard Template Library (STL) Overview .................................................................. 297Containers ................................................................................................................... 299Iterators ....................................................................................................................... 301Iterator Syntax .............................................................................................................. 303Non-Mutating Sequential Algorithms............................................................................. 305Mutating Sequential Algorithms .................................................................................... 307Sorting Algorithms ....................................................................................................... 309Numeric Algorithms...................................................................................................... 311auto_ptr Class ............................................................................................................. 313string Class ................................................................................................................. 315Labs ............................................................................................................................ 317

Chapter 15 - STL Containers ............................................................................................. 319

Chapter Objectives ...................................................................................................... 321Container Classes ....................................................................................................... 323Container Class Algorithms.......................................................................................... 325vector Class................................................................................................................. 327Additional vector Class Methods .................................................................................. 329deque Class ................................................................................................................ 331list Class ...................................................................................................................... 333set and multiset Classes .............................................................................................. 335map and multimap Classes.......................................................................................... 337Labs ............................................................................................................................ 339

Appendix A: Reference Sheets......................................................................................... 341

Constants, References, and Pointers ........................................................................... 343Input/Output.................................................................................................................. 345this Pointer .................................................................................................................. 347The Complete Report/Document Hierarchy .................................................................. 349

Page 8: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

viii C++ Programming

© 1995-2002 by itcourseware, LLC 6/02B

Appendix B: Templates ..................................................................................................... 351

Scenario ...................................................................................................................... 353Designing an Array Class ............................................................................................ 355Code for FloatArray ..................................................................................................... 357Code for IntArray.......................................................................................................... 359Templates .................................................................................................................... 361Template Syntax ........................................................................................................... 363Using Templates .......................................................................................................... 365Using Classes with Templates ..................................................................................... 367Additional Template Features ...................................................................................... 369Standard Template Library ........................................................................................... 371Labs ............................................................................................................................ 373

Appendix C: Sample Problems ........................................................................................ 377

Banking System - Problem Description........................................................................ 379Library Card Catalog - Problem Description ................................................................ 381Diagrams for Banking and Library Problems................................................................ 383Object Diagram - Banking............................................................................................ 385Event Trace Diagram - Banking ................................................................................... 387Object Diagram - Library.............................................................................................. 389Event Trace Diagram - Library ..................................................................................... 391

Appendix D: Other C++ Features ..................................................................................... 393

Namespaces ............................................................................................................... 395The static_cast and reinterpret_cast operator ............................................................. 397The dynamic_cast operator.......................................................................................... 399The const_cast Operator.............................................................................................. 401mutable Data Members ............................................................................................... 403The bool Datatype ....................................................................................................... 405new Operator Failure ................................................................................................... 407

Index ................................................................................................................................. 409

Page 9: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Course Introduction 9Chapter 1

© 1995-2002 by itcourseware, LLC 6/02

Chapter 1 - Course Introduction

Page 10: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

10 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Throughout the course, you will develop tools for keeping track of bug reports and bug fixes.You will learn the C++ language syntax and semantics through developing these tools.

In order to successfully make the transition from the procedural to the object-oriented mindset,you will analyze a problem and design a solution from an object-oriented perspective.

Page 11: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Course Introduction 11Chapter 1

© 1995-2002 by itcourseware, LLC 6/02

Course Objectives

Explain what Object-Oriented Programming is.

Identify abstractions to use as class names.

Know when and how to use inheritance.

Use polymorphism in C++ design.

Create templates.

Integrate exception handling into your programs.

Create overloaded functions.

Create and use overloaded operators.

Pass objects by reference.

Write constructors and destructors.

Put objects on the heap.

Define and use data and functions related to a class.

Organize OOP code classes so classes properly support eachother.

Page 12: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

12 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Page 13: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Course Introduction 13Chapter 1

© 1995-2002 by itcourseware, LLC 6/02

Audience: This course is designed for programmers who want tomove from procedural thinking to object-oriented thinking usingC++.

Prerequisites: This course assumes that the student is aprogrammer with experience programming in C.

Classroom Environment:

One workstation per student, with access to a C++development environment.

Course Overview

Page 14: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

14 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Suggested References (contd.)

Taylor, David A. 1997. Object Technology: A Manager's Guide, 2nd Edition. Addison-Wesley, Reading, MA. ISBN 0201309947.

Van Der Linden, Peter. 1994. Expert C Programming. Prentice Hall, Englewood Cliffs, NJ.ISBN 0131774298.

Wirfs-Brock, Rebecca, et al. 1990 Designing Object Oriented Software. Prentice Hall,Englewood Cliffs, NJ. ISBN 0136298257.

Page 15: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Course Introduction 15Chapter 1

© 1995-2002 by itcourseware, LLC 6/02

Suggested References

Cargill, Tom. 1992. C++ Programming Style. Addison-Wesley, Reading, MA.ISBN 0201563657.

Coplien, James O. 1991. Advanced C++ Programming Styles and Idioms.Addison-Wesley, Reading, MA. ISBN 0201548550.

Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming Language,2nd Edition. Prentice Hall, Englewood Cliffs, NJ. ISBN 0131103628.

Koenig, Andrew and Barbara E. Moo. 2000. Accelerated C++: PracticalProgramming by Example. Addison-Wesley, Reading, MA. ISBN 020170353X.

Lippman, Stanley B. and Josee Lajoie. 1998. C++ Primer, 3rd Edition. Addison-Wesley, Reading, MA. ISBN 0201824701.

Lippman, Stanley B. 1996. Inside the C++ Object Model. Addison-Wesley, Reading,MA. ISBN 0201834545.

Meyers, Scott. 1997. Effective C++: 50 Specific Ways to Improve Your Programsand Designs, 2nd Edition. Addison-Wesley, Reading, MA. ISBN 0201924889.

Meyers, Scott. 1995. More Effective C++: 35 New Ways to Improve Your Programsand Designs. Addison-Wesley, Reading, MA. ISBN 020163371X.

Plauger, P.J., et al. 2000. The C++ Standard Template Library. Prentice Hall,Englewood Cliffs, NJ. ISBN 0134376331.

Plauger, P.J. 1994. The Draft Standard C++ Library. Prentice Hall, Englewood Cliffs,NJ. ISBN 0131170031.

Plauger, P.J. 1991. The Standard C Library. Prentice Hall, Englewood Cliffs, NJ.ISBN 0131315099.

Stroustrup, Bjarne. 2000. The C++ Programming Language, 3rd Edition. Addison-Wesley, Reading, MA. ISBN 0201700735.

Stroustrup, Bjarne. 1994. The Design and Evolution of C++. Addison-Wesley,Reading, MA. ISBN 0201543303.

Page 16: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

16 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Page 17: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Classes 17Chapter 2

© 1995-2002 by itcourseware, LLC 6/02

Chapter 2 - Classes

Page 18: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

18 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

User Requirements for the Application

1. Quality Assurance personnel need to be able to record bugs they find when testingproducts under development. Information such as when the bug was found, the severity ofthe bug, and a description of the bug, need to be captured.

2. As developers fix bugs, they'll need to enter their fixes into the system. The informationcaptured for the fix includes the developer that fixed the bug, which bug was fixed, and thedate of the fix.

3. The QA organization currently has an inefficient manual system of tracking memos andstatus reports. They would like to automate this by entering memos and status reportson-line and having them automatically routed and tracked. In addition to the text, thesememos and reports also have a date and time of creation.

4. There needs to be support for administrative functions such as these: printing out the list ofbugs, fixes, and status reports; archiving old information; and searching for specific reportsand fixes.

Your role will be to create the tools that someone else will use to build this application.

Scenario

Bug reports and bug fixes will need to have a date associated with them. Our first step is todevelop a Date type.

We need to implement our Date type so that it can be used with operations that we provide.Furthermore, any code using our Date type should not be allowed to directly access itsinternal details.

What data should our Date type have?

Page 19: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Classes 19Chapter 2

© 1995-2002 by itcourseware, LLC 6/02

Chapter Objectives

Define a class with data and methods.

Define what an object is and be able to declare one.

Describe what a data member is.

Describe what a method is and how to invoke it.

Describe what a namespace is.

Use access specifiers to enforce encapsulation.

Page 20: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

20 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Let's create the Date structure and a main() to test it out:

Date.cpp

struct Date {int day;int month;int year;

};

void main() {Date today;today.day = 2;today.year = 1998;today.month = 10;today.day = today.day + 1;

}

Remember, you need the semicolon after a struct definition because you could make avariable of that type, for instance:

struct Date {int day;int month;int year;

} globaldate;

Page 21: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Classes 21Chapter 2

© 1995-2002 by itcourseware, LLC 6/02

Creating a Data Structure

A struct's data members describe the individual features of acomplex type of data.

struct Date {int day;int month;int year;

};

Members of the structure can be built-in types or otherstructures.

Once you've defined a struct, you can declare variablesrepresenting distinct instances of the struct's type.

Date today, tomorrow;

Use dot notation to access members of the structure.

today.day = 2;today.year = 1998;today.month = 10;today.day = today.day + 1;

What functions are we going to need to service this data structure?

Page 22: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

22 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Let's add in a set() method with its code:

Date.cpp

struct Date {int day;int month;int year;void set(int m, int d, int y);

};

void Date::set(int m, int d, int y){

day = d;month = m;year = y;

}

void main(){

Date today;today.set(10,2,1998);today.day++;

}

Page 23: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Classes 23Chapter 2

© 1995-2002 by itcourseware, LLC 6/02

Methods

structs have always been part of the C language.

C++ adds the ability to define functions within a struct.

To call these functions, use dot notation, just like structure data.

Date today;today.set(10, 2, 1998);

A function defined together with its data is a method.

Methods are also called member functions, operations, ormessages, depending on a programmer's background.

"Member function" is often used by people with a C/C++ background.

"Method" or "message" is more common from people with a pure OO background.

When writing the implementation of the method, you must specifywhich structure the method belongs to.

The name of a method is preceded by the name of thestructure, plus the scope operator (::).

void Date::set(int m, int d, int y)

- This is the set() method for Date (other structuresmight also have set() methods).

Page 24: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

24 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Both of these main() functions modify today's day, month, and year.

void main(){

Date today;

today.day = 2;today.year = 1998;today.month = 10;today.day = today.day + 1;

}

void main(){

Date today;

today.set(10, 2, 1998);today.day++;

}

Page 25: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Classes 25Chapter 2

© 1995-2002 by itcourseware, LLC 6/02

Methods always run in the context of an invoking object.

Date today;today.set(10, 2, 1998);

set() is called within the context of the Date object today.

Within Date's set() method, day = d sets today's daymember to 2.

void Date::set(int m, int d, int y){

day = d;month = m;year = y;

}

Within any Date member function, there will always be available aday, month, and year belonging to the invoking object.

Date tomorrow;tomorrow.set (10,3,1998);

In this case, the set() method sets tomorrow's day,month, and year.

Object Scope

Page 26: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

26 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Now, let's add a display() method with its code. We must include iostream and theinformation about the std namespace:

Date.cpp

#include <iostream>using namespace std;

struct Date {int day;int month;int year;void set(int m, int d, int y);void display(void);

};

void Date::set(int m, int d, int y){

day = d;month = m;year = y;

}

void Date::display(void){

cout << month << '/';cout << day << '/';cout << year << endl;

}

void main(){

Date today;

today.set(10, 3, 1998);today.display();today.day++;today.display();

}

Page 27: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Classes 27Chapter 2

© 1995-2002 by itcourseware, LLC 6/02

C++ I/O is done through streams, which provide you with aconsistent interface to consoles, files, etc.

cout is an output stream connected to the program'sstandard output destination.

cin is an input stream connected to the program's standardinput source.

cerr is an output stream connected to the program'sstandard error destination.

Use the << operator to send data to an output stream.

cout << "Hello, world!\n";cerr << "Can't find my file!" << endl;

endl sends a newline to the output stream, and then flushesthe stream.

Use the >> operator to get data from an input stream.

int i;cin >> i;

At least for testing purposes, most of your classes, or structures,will need an easy way to be output, such as a display() method.

C++ Input and Output

Page 28: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

28 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

The Evolution of Header Files

Older style C and C++ header files have a .h extension. These are NOT the same as the newheader files without the extensions. The main difference is the use of namespaces in the newC++ header files.

Older compilers do not understand the use of namespaces. So newer compilers aredistributed with two sets of header files.

You should NOT mix the usage of old and new header files.

Examples:

C++ header files no longer have the .h extension.

Old C++ header files New C++ header files

iostream.h iostreamfstream.h fstreamlimits.h limits

C header files no longer have the .h extension, and start with the letter c.

Old C header files New C header files

stdio.h cstdiostdlib.h cstdlibstring.h cstring

Page 29: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Classes 29Chapter 2

© 1995-2002 by itcourseware, LLC 6/02

Namespaces

All of the classes that are part of the standard C++ library are in anamespace called std.

Namespaces are one of the features that C++ uses formodularity.

Including a header file makes all the constructs in the file available.

A statement in the format of using namespace followed bythe namespace name causes all of the parts of thatnamespace to be integrated into the global namespace.

using namespace std;

- It may be desirable to only include those that are goingto be used.

In this course, we will provide a general using statement forsimplicity's sake.

To use cout, cin, and endl without the std:: notation, dothe following:

#include <iostream>#include <fstream>using std::cout;using std::cin;using std::endl;

Without the using line, the compiler wouldn't recognizestandard classes such as ostream, the data type for coutand cerr.

Page 30: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

30 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

The built-in types that you use, such as float, are abstract data types. Instead of havingmethods to modify their data, you have operators such as =,+, and -.

float f;f = 3.14;f = f + 6.8;

A float is abstract because you, as a user of a float, don't care that it is stored in IEEEformat.

Page 31: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Classes 31Chapter 2

© 1995-2002 by itcourseware, LLC 6/02

Data Abstraction

When you separate the way you access and modify data from theway the data is stored, you're using data abstraction.

This usually means that the user of a data structure cannot (orshould not) directly access its data.

Methods are provided to get and set the data values.

This separates user code from implementation code.

User code is any code that is not part of the data structure.

Implementation code is any method defined within thestructure.

If only the implementation code has access to the data, we haveachieved data abstraction.

Data abstraction makes maintenance easier because the data andthe code that can modify it are grouped together.

Page 32: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

32 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

We often speak of user code. This is any code that is not part of your structure. For example,the main() function you wrote uses your Date structure.

The keywords public and private can appear in any order and as many times as desired.

For example:

struct Date {public: void set(int m, int d, int y);private: int day; int month;public: void display(void);private: int year;};

Investigate:

Given that C++ is a superset of C, can you think of any ways of getting around private?(Keeping in mind that it's a bad idea!)

Page 33: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Classes 33Chapter 2

© 1995-2002 by itcourseware, LLC 6/02

You encapsulate data within a structure by restricting whichmethods have access to it.

C++ provides access specifiers to identify which methods in anapplication can access the various parts of a structure.

The public and private access specifiers enforce dataencapsulation.

struct Date {private: int day; int month; int year;public: void set(int m, int d, int y); void display(void);};

Members of a structure declared to be public can be used fromany method in an application.

Members that are declared private can only be used bymethods within this structure (called member functions).

So public member functions are used to access privatedata!

Enforcing Data Encapsulation

Page 34: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

34 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Date.h

#ifndef _DATE_H_#define _DATE_H_ 1

struct Date {public:

void set(int m, int d, int y);void display(void);

private:int day;int month;int year;

};

#endif // #ifndef _DATE_H_

Date.cpp

#include <iostream>using namespace std;

#include "Date.h"

void Date::set(int m, int d, int y){

day = d;month = m;year = y;

}

void Date::display(void){

cout << month << '/';cout << day << '/';cout << year << endl;

}

main.cpp

#include "Date.h"

void main(){

Date today;

today.set(10, 3, 1998);today.display();today.set(10, 6, 1998);today.display();

}

Page 35: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Classes 35Chapter 2

© 1995-2002 by itcourseware, LLC 6/02

File Organization

Files are divided up for organization and compile efficiency.

Structures like Date are often put into two files:

The header which has the declaration.

The source file which has the code for the methods (thedefinition).

Date.h — the structure declaration.

Date.cpp — the structure definition (implementation code).

main.cpp — the application (user code).

Divide Date.cpp into Date.h, Date.cpp, and main.cpp.

Don't forget! #include "Date.h" in Date.cpp andmain.cpp.

Page 36: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

36 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Notation for classes:

Nameattributesmethods

For example:

Datedaymonthyear

setdisplay

Either one, or both, of the bottom two compartments are optional when drawing a ClassDiagram.

Page 37: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Classes 37Chapter 2

© 1995-2002 by itcourseware, LLC 6/02

Classes in C++

Class is the OO term for a data type that uses data encapsulationand data abstraction.

The C++ keyword class, like struct, declares the data andmethods of a class.

Semantically, the only difference between a struct and aclass is that a struct's members are public by default,and a class's members are private by default.

Use a class when creating a data type that encapsulates aninterface and its implementation.

Use struct when a structure in the "traditional C" sense isneeded — typically only for data.

Let's turn our Date into a class.

From:

struct Date {...} ;

To:

class Date {...} ;

Page 38: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

38 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Notation for objects:

name:Type

attribute=value

For instance:

today:Date

day = 5month = 10year = 1998

The second compartment is optional when drawing Object Diagrams.

ind:Date

day = 4month = 7year = 1776

Page 39: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Classes 39Chapter 2

© 1995-2002 by itcourseware, LLC 6/02

Objects

An object is an instance of a class; so, when you make a variableof type Date, you're making a Date object.

Date today;today.set(10, 2, 1998);

In this case, today is an object of type Date; a Date object.

Each Date object has its own day, month, and year values.

Date ind;ind.set (7,4,1776);

Dates in different memory locations are different Dateobjects.

Page 40: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

40 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Page 41: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Classes 41Chapter 2

© 1995-2002 by itcourseware, LLC 6/02

For normal methods, the this pointer is a pointer to the invokingobject.

When a method is called, an additional parameter, the thispointer, is passed.

The call works like a standard C function, but the this pointeris hidden and never declared in the method header.

The this pointer gives access to the object's data.

- A method call such as christmas.set(12,25,2001)would cause the header of the effective call to look likethis (with this pointing to christmas):

void set( Date* this, int month, int day, int year)

When a normal function is called, nothing special is added.

this Pointer

Page 42: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

42 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Page 43: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Classes 43Chapter 2

© 1995-2002 by itcourseware, LLC 6/02

Labs

1. Add a new method called increment() to your Date class that adds one dayto its Date object. Code for the simplest case right now (ignore leap years, endsof months, etc.).

2. Add a decrement() method to your Date class too. Again, code for thesimplest case.

3. Write code in your main() function to test your new methods. Can you use themtogether to easily test each other?

4. Create a Time class that keeps track of the hour and the minute. Write aset() method that takes as its arguments an hour and a minute.

5. Add a display() method to your Time class.

6. Look up setw(), cout.width(), and cout.fill() in the ReferenceSheets appendix. Use those functionalities of C++ I/O to make sure your Timeclass displays 12:05 correctly.

7. (Optional) A year is a leap year when it is divisible by 4 but not divisible by 100(except when it is divisible by 400). There are 31 days in January, March, May,July, August, October, and December.

Give your Date class data sanity checking, and make sure your increment()and decrement() methods work correctly.

8. (Optional) Add data sanity checking to your Time class now. How are you goingto differentiate between a.m./p.m.?

9. (Optional) Leap year doesn't apply to dates before September 1752 (that's whenit started). Make sure your Date class doesn't try to apply leap year rules beforethen. Also, 9/3/1752 through 9/13/1752 don't exist; make sure your Date classwon't allow them to be used.

Page 44: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

44 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Page 45: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Inheritance 73Chapter 4

© 1995-2002 by itcourseware, LLC 6/02

Chapter 4 - Inheritance

Page 46: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

74 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Scenario

Now that we have our Report class, we are going to build upon it to create a class that will beused throughout our system. Since the Bugreport class will have all the functionality theReport class has, plus more, we will use the C++ feature called inheritance to avoidduplicating work we've already done.

Page 47: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Inheritance 75Chapter 4

© 1995-2002 by itcourseware, LLC 6/02

Chapter Objectives

Describe how inheritance works.

Derive a class from another class.

Explain what overriding means.

Use access specifiers with inheritance.

Explain protected access.

Page 48: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

76 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Class Diagram: Terminology:

Bugreport inherits from Report.Bugreport is a descendant of Report.Bugreport is a child of Report.Bugreport is a derived class.Bugreport is a subclass.Bugreport is a Report.Report is an ancestor of Bugreport.Report is a parent of Bugreport.Report is a base class.Report is a superclass.

Bugreport bug_a;

bug_a

Report

bug_id severity

Bugreport

Report

Report r;

r

rep_date rep_time rep_desc

A Look at Memory:

Page 49: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Inheritance 77Chapter 4

© 1995-2002 by itcourseware, LLC 6/02

Inheritance

Inheritance allows us to build one data type from another.

This is also called specialization, because we are creating aspecialized version of a generic class.

- A Bugreport is a special kind of Report; it inheritsfrom the Report class.

Specify inheritance when creating the derived class.

class Bugreport : public Report {

Bugreport will now have all the data and methods thatReport does, plus any that we define in Bugreport.

- A Bugreport contains everything that a Reportcontains, plus more.

Bugreport.h

#ifndef _BUGREPORT_H_#define _BUGREPORT_H_ 1

#include "Report.h"

class Bugreport : public Report {public:

Bugreport(void);~Bugreport(void);

void display(void);void disp_id(void);

private:int bug_id;int severity;

};

#endif // #ifndef _BUGREPORT_H_

What would Bugreport's methods look like?

Page 50: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

78 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Bugreport.cpp

#include <iostream>using namespace std;

#include "Bugreport.h"#include "debug.h"

Bugreport::Bugreport(void) : bug_id(0), severity(0){

DEBUG << "Bugreport: default ctor" << endl;}

Bugreport::~Bugreport(void){

DEBUG << "Bugreport: dtor" << endl;}...void Bugreport::display(void){

disp_id();cout << "Severity: " << severity << endl;Report::display();

}

void Bugreport::disp_id(void){

cout << "ID: " << bug_id << endl;}

Page 51: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Inheritance 79Chapter 4

© 1995-2002 by itcourseware, LLC 6/02

Bugreport

When a superclass method (Report::display()) has the samesignature as a subclass method (Bugreport::display()), thesubclass method is said to override the superclass method.

Bugreport's display() method overrides Report's.

When you call display() on a Bugreport object,Bugreport's display() method gets called.

If Bugreport didn't have a display() method, then callingdisplay() on a Bugreport object would invoke Report'sversion.

Often the subclass's method will call the superclass's version, andthen add more functionality (like we want to do with display()).

In Bugreport's case, it would be illegal to try to accessReport's rep_date, rep_time, and rep_desc direction.

- They are all private member data of Report, soBugreport doesn't have access to them.

hey are all private memberThe only way we can display them is by calling Report'sversion of display(), which has the code we want.

- This is data encapsulation again, protecting Report'sdata and making it easier to debug the Bugreportclass.

To call a superclass method, put the name of the superclass andthe scope operator before the method's name.

Report::display();

Page 52: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

80 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Page 53: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Inheritance 81Chapter 4

© 1995-2002 by itcourseware, LLC 6/02

Protected Access Modifier

Methods of a subclass cannot access private data or methodsdefined in the superclass.

If you want a method or data member in the superclass to beaccessible by subclass methods, use the protected accessspecifier.

The protected specifier is an alternative to private orpublic, and is used the same way.

class Date {protected:

int day;int month;int year;

public:...};

Normally, use private to enforce stricter data encapsulation, butwhen you're designing a class to be a superclass, be aware thatyou can make data and methods protected instead.

This works well for internal utility methods that the subclasscould take advantage of, but which are not appropriate forexternal classes.

Page 54: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

82 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

The box shows where either public, protected, or private can go.

#ifndef _REPORT_H_#define _REPORT_H_ 1

#include "Date.h"#include "Time.h"

#define MAX_CHAR_SIZE 200class Report {private: Date rep_date; Time rep_time; char rep_desc[MAX_CHAR_SIZE];public:

...};

#endif // #ifndef _REPORT_H_

Bugreport.h

#ifndef _BUGREPORT_H_#define _BUGREPORT_H_ 1

#include "Report.h"

class Bugreport : Report {public:

Bugreport(void);~Bugreport(void);

void display(void);void disp_id(void);

private:int bug_id;int severity;

};

#endif // #ifndef _BUGREPORT_H_

Page 55: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Inheritance 83Chapter 4

© 1995-2002 by itcourseware, LLC 6/02

Access and Inheritance

The words public, protected, and private are used to twoways in C++.

For data members and methods, they determine access.

For classes, they determine the type of inheritance.

Regardless of how Bugreport derives from Report, Bugreportdoes not have access to Report’s private data.

If Bugreport is publicly derived from Report, Report’s set(),display() and display_desc() methods are public toBugreport.

This is the type of inheritance used 99% of the time.

If Bugreport uses protected derivation of Report, Report’s,display() and display_desc() methods are protected inBugreport.

This is rarely used.

It means that you want the base-class members of aninstantiated object to be accessible only to the subclass andclasses that derive from it.

If Bugreport uses private derivation of Report, Report’s,display() and display_desc() methods are private toBugreport.

This is also rarely used.

It means that you want the base-class members only to beaccessible to the subclass.

Page 56: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

84 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Page 57: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Inheritance 85Chapter 4

© 1995-2002 by itcourseware, LLC 6/02

Constructors and Inheritance

Subclasses do not inherit constructors and destructors.

The subclass needs its own constructors and destructors towork with the new data defined in the subclass.

Even though Report declares a copy constructor that takesa Report object as its argument, Bugreport does not inheritthis constructor; we have no way of creating a Bugreportobject from a Report object.

However, a subclass can use the superclass constructors anddestructors to initialize and clean up the superclass data.

The default constructor is called for the Report parts of aBugreport object.

Otherwise, there would be no way to initialize private datawithin the Report parts of Bugreport; Bugreport methodsaren't allowed to access them directly.

Construction starts at the top of the class hierarchy.

For each level, first the base class constructor is called, thenthe member object constructors are called.

Page 58: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

86 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Bugreport.h

#ifndef _BUGREPORT_H_#define _BUGREPORT_H_ 1

#include "Report.h"

class Bugreport : public Report {public:

Bugreport(void);~Bugreport(void);Bugreport(const Bugreport& br);Bugreport(Date d, Time t, char *desc, int id, int sev);

void display(void);void disp_id(void);

private:int bug_id;int severity;

};

#endif // #ifndef _BUGREPORT_H_

Bugreport.cpp

#include <iostream>using namespace std;

#include "Bugreport.h"#include "debug.h"

Bugreport::Bugreport(void) : bug_id(0), severity(0){

DEBUG << "Bugreport: default ctor" << endl;}Bugreport::~Bugreport(void){

DEBUG << "Bugreport: dtor" << endl;}Bugreport::Bugreport(const Bugreport& br) : Report(br), bug_id(br.bug_id),

severity(br.severity){

DEBUG << "Bugreport: copy ctor" << endl;}Bugreport::Bugreport(Date d, Time t, char *desc, int id, int sev) :

Report(d, t, desc), bug_id(id), severity(sev){

DEBUG << "Bugreport: date time char * int int ctor" << endl;}void Bugreport::display(void){

disp_id();cout << "Severity: " << severity << endl;Report::display();

}void Bugreport::disp_id(void){

cout << "ID: " << bug_id << endl;}

Page 59: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Inheritance 87Chapter 4

© 1995-2002 by itcourseware, LLC 6/02

Initialization Lists Revisited

When you want to call a superclass constructor other than thedefault, you specify it in the initialization list.

Bugreport::Bugreport(const Bugreport &br) :Report(br), severity(br.severity),bug_id(br.bug_id)

{DEBUG << "Bugreport: copy ctor" << endl;

}

Report doesn't have a constructor that takes a Bugreport object,but the code works anyway because a Bugreport is-a Report.

br contains all of the parts that the Report constructorneeds.

This is called "upcasting," because you're going up theinheritance tree.

Page 60: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

88 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Virtual Inheritance:

Multiple Inheritance:

LogFile

Logchar *name

File

char *name

Multiple Copies of Base Class:

PersonWindow

InputWindow DataWindow

Window

char* title

Window

char* title

PersonWindow

InputWindow DataWindow

Window

char* title

Page 61: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Inheritance 89Chapter 4

© 1995-2002 by itcourseware, LLC 6/02

Multiple Inheritance

You can inherit a subclass from multiple superclasses.

The subclass will inherit all member data and methods foreach of its superclasses.

Subclass is-a superclass must be true for each superclass.

Two main problems exist when you try to use multiple inheritance:name collision and diamond hierarchies.

Name collisions happen when multiple base classes havemember data or methods of the same name.

class LogFile:public Log, public File {...}

- In child methods, specify which name you want toaccess by using the class name and the scopeoperator.

File::name[0] = '\0';

Diamond hierarchies happen when multiple base classeshave the same superclass themselves.

- By default, each PersonWindow will have two copies ofWindow.

- This is resolved with virtual inheritance from theWindow class.

class InputWindow : virtual public Window {};class DataWindow : virtual public Window {};

Page 62: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

90 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Page 63: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Inheritance 91Chapter 4

© 1995-2002 by itcourseware, LLC 6/02

Labs

1. Create an ExternalBugReport class. We need it to keep track of bugs forproducts that our company doesn't have control of (the OS and other softwareprovided by external suppliers).

It should inherit from Bugreport, plus also have information on which companyit is (a string like rep_desc in Report), which product the bug is in (also astring), and a status, which can be:

The bug is logged.We have informed the company of the bug.The company has confirmed receiving our bug report.The company has reproduced the bug.The company has told us they won't be fixing the bug.The bug has been fixed and the fix will be in the next major release of the product.The bug has been fixed and the fix will be in the next minor release of the product.The bug has been fixed and we are currently using the fixed version of the product.

Hint: Implement the status codes as constants or as an enum.

2. Write the display() and display_status() methods for theExternalBugReport class. display_status() will print a stringdescribing the current status as presented above.

3. Write a set of methods that allow us to set the values for the new member data.

4. Create a default constructor for the ExternalBugReport class.

5. Add a copy constructor.

6. Write the destructor for the ExternalBugReport class.

7. Write a constructor for the ExternalBugReport class that takes a Date, aTime, a char*, two ints, two char*s, and a status.

Continued . . .

Page 64: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

92 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Remember that cout is an ostream object, hooked up to the standard output destination. Asubclass (usually) of ostream, ofstream, handles outputting to a file. Because it inheritsfrom ostream, we already know how to use it (just like you do cout). The way you createone is to pass the name of the file to the constructor:

ofstream outputfile("output.txt");

or if you want to append to an existing file:

ofstream outputfile("output.txt", ios::app);

Then use it like cout:

outputfile << "Hello, world!" << endl;

The other very useful method you might use is for ifstream, which allows you to read anentire line at once.

ifstream inputfile("input.txt");char buffer[80];

inputfile.getline(buffer, 80);

The second argument tells it the maximum size of the buffer, so it truncates the line if it is toolong to fit in the memory you have allocated.

Page 65: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Inheritance 93Chapter 4

© 1995-2002 by itcourseware, LLC 6/02

Labs (contd.)

8. (Optional) Object Persistence is a term used to describe situations where wewant an object to exist over multiple runs of a program. This can mean storinginformation to a text file, a binary file, or even a database.

Create two new methods for your Report class. The first:

void Report::writeToStream(ostream &os);

will output the Report object onto that output stream. The second:

Report::Report(istream &is);

is a constructor that will read in the Report object from the input stream. Theformats for each must be consistant with each other (we want to be able to outputthe object into a file, then re-create the object back in memory again later byreading the same file).

A simple version of the code that should run would be:

void main(){

Date d(10, 15, 1998);Time t(8, 6);Report r(d, t, "Blue screen of death.");ofstream out("output.rpt");

r.display();r.writeToStream(out);out.close();

ifstream in("output.rpt");Report another(in);another.display();

}

Continued . . .

Page 66: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

94 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Page 67: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Inheritance 95Chapter 4

© 1995-2002 by itcourseware, LLC 6/02

Labs (contd.)

9. (Optional) Building on the last exercise, now write the equivalent methods for yourBugreport class, and make sure they work.

10. (Optional) Finally, write the equivalent methods for your ExternalBugreportclass.

Page 68: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

96 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Page 69: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Overloaded Functions 227Chapter 11

© 1995-2002 by itcourseware, LLC 6/02

Chapter 11 - Overloaded Functions

Page 70: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

228 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Scenario

Currently, once Report, Bugreport, and ExternalBugreport objects are created,there is no good way to set their data to different values. We would like to be able to do thiswith a set() method like we have for Time and Date. A Report set() method wouldprobably need to set rep_date and rep_time with new Dates and Times. So we'll needa set() method in Date that takes another Date, and a set() method in Time that takesanother Time.

Page 71: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Overloaded Functions 229Chapter 11

© 1995-2002 by itcourseware, LLC 6/02

Chapter Objectives

Describe what an overloaded function is.

Know what conditions are required for overloading.

Describe how const affects overloading.

Declare and use default arguments.

Page 72: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

230 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Page 73: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Overloaded Functions 231Chapter 11

© 1995-2002 by itcourseware, LLC 6/02

Function Overloading

Function overloading means two functions have the same name buttake different arguments.

In this case, let's create a set() method for the Date classthat takes a constant reference to a Date object.

Date.h...class Date {...

void set(int m, int d, int y);void set(const Date &dt);

...};...

The code will simply copy the values from the Date passed.

Date.cpp...void Date::set(const Date &dt){

day = dt.day;month = dt.month;year = dt.year;

}

Page 74: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

232 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Page 75: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Overloaded Functions 233Chapter 11

© 1995-2002 by itcourseware, LLC 6/02

Using Overloaded Functions

Using an overloaded function is just like using any other function.

The only difference is the number and types of argumentsyou pass in.

The compiler takes the arguments you have given to it, andtries to match it to a function prototype.

- If it doesn't find a function that matches exactly, thecompiler will try implicit casting with the availablemethods.

This means that you can't have two overloaded functions withthe same name that take the same arguments.

- The number and type of the arguments is the only waythe compiler knows they are different.

We can use Date 's overloaded set() method to copy a Dateobject to an existing date object.

We couldn't do this with the copy constructor, becauseconstructors create an object, and we have already createdone.

void main(){...

Date ind(7, 4, 1776), ind_copy;ind.display();ind_copy.display();ind_copy.set(ind);

... ind_copy.display();}

Page 76: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

234 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Page 77: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Overloaded Functions 235Chapter 11

© 1995-2002 by itcourseware, LLC 6/02

Rules for Overloading

You can overload based on the number of arguments:

void a_function(int a, int b);

is different from

void a_function(int a, int b, int c);

The compiler determines which one you mean by how manyarguments you pass it.

You can overload based on the types of the arguments.

void b_function(int a);

is different from

void b_function(Date d);

The compiler determines which one you are calling by thetypes of the arguments you pass it.

You cannot overload based on the types of the return values.

int c_function(void);

is the same as

float c_function(void);

The compiler determines which function to call before itinspects return types.

This results in a compile error.

Page 78: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

236 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Page 79: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Overloaded Functions 237Chapter 11

© 1995-2002 by itcourseware, LLC 6/02

Overloading Based on Constness

You can overload based on whether a member function is constor not.

void Date::display(void);

would be different from

void Date::display(void) const;

It calls the const version if you invoke the method on aconst object.

This allows slightly different behavior based on whether theinvoking object is const or not.

- This concept is especially useful with overloadedoperators, which we'll cover later.

One issue worth noting here: During lab, you changed yourDocument class's virtual void display() method to beconst.

Because you can overload based on const, you mustchange derived class's display method to be const also.

- Otherwise, you're talking about two different methods!

- Since display() is pure virtual in the base class, itmust be overridden in the derived classes.

- Therefore, unless you make it const in the derivedclasses, all the derived classes are still abstract!

Page 80: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

238 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Date.h

#ifndef _DATE_H_#define _DATE_H_ 1

class Date {public:

Date(void); // default ctor~Date(void); // dtorDate(const Date& d);Date(int m, int d, int y=1970);

void set(int m, int d, int y);void set(const Date &dt);

void display(void) const;void increment(void);void decrement(void);

private:int day;int month;int year;

};

#endif // #ifndef _DATE_H_

No type checking is done by the compiler to determine which arguments have been provided and whicharguments should use the defaults. When the function is defined/declared, any default arguments must bespecified from right to left. When the function is invoked, any missing arguments are assumed to be theright-most arguments. For Example:

class Date {...

Date(int m=1, int d=1, int y=1970);...};

main(){ Date somedate(11);}

The object somedate is using the default arguments for setting the day and year.

Page 81: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Overloaded Functions 239Chapter 11

© 1995-2002 by itcourseware, LLC 6/02

Default Arguments

There are times when you want one overloaded function to be justlike another, only not specifying one of the arguments.

For instance, we could have a two-int constructor for Datethat took a month and day, with the year set to a default value.

Date::Date(int m, int d):month(m), day(d), year(1970) { }

But this causes redundant code.

In C++, you can specify default values for arguments in thedeclaration (class definition).

class Date {...public:

Date(int m, int d, int y=1970);...};

No code changes are necessary, if the user code passes intwo ints, the third (y) will be assigned the default value.

Default argument values must be specified starting with thelast argument and working left.

- You cannot skip an argument.

Date(int m=1, int d=1, int y=1970); // okDate(int m=1, int d, int y=1970); // illegalDate(int m=1, int d=1, int y); // illegal

Page 82: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

240 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

main.cpp

...#include "Date.h"...main(){... Date today(12,20); today.display();}

Investigate:

Note the ambiguity in the following code:

inv_1.cpp

#include <iostream>

using namespace std ;

void print_number(float fl){ cout << fl << endl;}

void print_number(double dbl){ cout << dbl << endl;}

void main(void){ int x=20; print_number(x);}

The integer x can be converted to either a float or a double.How can the bold line be modified to eliminate the ambiguity?

Page 83: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Overloaded Functions 241Chapter 11

© 1995-2002 by itcourseware, LLC 6/02

Invoking Functions with Default Arguments

Beware of the potential for ambiguities in calling functions that havedefault arguments.

If you have overloaded a function name and you're usingdefault arguments, you can get into trouble.

class Date {...public:

Date(int m, int d, int y=1998);Date(int m, int d);

...};

void main(){

Date today(10, 25); // Which one is // called?

...}

The answer is neither; the above will result in a compile errorbecause the compiler doesn't know what you mean.

Otherwise, call the functions or methods normally, omitting anyarguments when you want to use their default value.

Page 84: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

242 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02

Page 85: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Overloaded Functions 243Chapter 11

© 1995-2002 by itcourseware, LLC 6/02

Labs

1. Write a set() method for Time that takes a Time object as its argument.

2. Add a set() method to your String class that takes a String object. Whydon't we need to overload the set() method with one that takes a char array?Be careful with this function, there are memory issues involved . . .

3. Create two set() methods for Report, one that takes a Report object as itsonly argument, and another that takes three arguments: a Date object, a Timeobject, and a String object.

4. Add two set() methods to Bugreport, one that takes a Bugreport object,and one that takes a Date object, a Time object, a String object, and one int(the severity).

5. Make two set() methods for the Bugfix class, one whose argument is aBugfix object, the other taking three arguments: the fix date, the author of the fix,and a pointer to the Bugreport object that shows which bug was fixed.

6. Write two set() methods for ExternalBugreport , one that takes anExternalBugreport object, another that takes a Date object, a Time object,a String object, an int (severity), two more String objects, and a status.

Page 86: C++ Programming - · PDF fileAdvanced C++ Programming Styles and Idioms. Addison-Wesley, Reading, MA. ISBN 0201548550. Kernighan, Brian W. and Dennis M. Ritchie. 1998. The C Programming

Notes

244 C++ Programming

© 1995-2002 by itcourseware, LLC 6/02