Upload
others
View
0
Download
0
Embed Size (px)
Citation preview
Many of the designations used by manufacturers and sellers to distinguish their products are claimedas trademarks. Where those designations appear in this book, and the publisher was aware of atrademark claim, the designations have been printed with initial capital letters or in all capitals.
The authors and publisher have taken care in the preparation of this book, but make no expressed orimplied warranty of any kind and assume no responsibility for errors or omissions. No liability isassumed for incidental or consequential damages in connection with or arising out of the use of theinformation or programs contained herein.
The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases orspecial sales, which may include electronic versions and/or custom covers and content particular toyour business, training goals, marketing focus, and branding interests. For more information, pleasecontact:
U. S. Corporate and Government Sales(800) [email protected]
For sales outside the U. S., please contact:
International [email protected]
Visit us on the Web: www.awprofessional.com
Library of Congress Cataloging-in-Publication Data
Lippman, Stanley B.C++ primer / Stanley B. Lippman, Josée Lajoie, Barbara E. Moo. — 4th ed.
p. cm.Includes index.ISBN 0-201-72148-1 (pbk. : alk. paper)1. C++ (Computer program language) I. Lajoie, Josée. II. Moo, Barbara E. III. Title.
QA76.73.C153L57697 2005005.13’3–dc22 2004029301
Copyright c© 2005 Objectwrite Inc., Josée Lajoie and Barbara E. Moo
All rights reserved. Printed in the United States of America. This publication is protected bycopyright, and permission must be obtained from the publisher prior to any prohibited reproduction,storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical,photocopying, recording, or likewise. For information regarding permissions, write to:
Pearson Education, Inc.Rights and Contracts DepartmentOne Lake StreetUpper Saddle River, NJ 07458
ISBN 0-201-72148-1
January201011th PrintingText printed in the United States on recycled paper at in Stoughton, Massachusetts.Courier Stoughton
Preface
C++ Primer, Fourth Edition, provides a comprehensive introduction to the C++ lan-guage. As a primer, it provides a clear tutorial approach to the language, enhancedby numerous examples and other learning aids. Unlike most primers, it also pro-vides a detailed description of the language, with particular emphasis on currentand effective programming techniques.
Countless programmers have used previous editions of C++ Primer to learnC++. In that time C++ has matured greatly. Over the years, the focus of thelanguage—and of C++ programmers—has grown beyond a concentration on run-time efficiency to focus on ways of making programmers more efficient. With thewidespread availability of the standard library, it is possible to use and learn C++more effectively than in the past. This revision of the C++ Primer reflects these newpossiblities.
Changes to the Fourth Edition
In this edition, we have completely reorganized and rewritten the C++ Primer tohighlight modern styles of C++ programming. This edition gives center stage tousing the standard library while deemphasizing techniques for low-level program-ming. We introduce the standard library much earlier in the text and have reformu-lated the examples to take advantage of library facilities. We have also streamlinedand reordered the presentation of language topics.
In addition to restructuring the text, we have incorporated several new el-ements to enhance the reader’s understanding. Each chapter concludes with aChapter Summary and glossary of Defined Terms, which recap the chapter’s mostimportant points. Readers should use these sections as a personal checklist: If youdo not understand a term, restudy the corresponding part of the chapter.
We’ve also incorporated a number of other learning aids in the body of the text:
• Important terms are indicated in bold; important terms that we assume arealready familiar to the reader are indicated in bold italics. Each term appearsin the chapter’s Defined Terms section.
• Throughout the book, we highlight parts of the text to call attention to im-portant aspects of the language, warn about common pitfalls, suggest goodprogramming practices, and provide general usage tips. We hope that thesenotes will help readers more quickly digest important concepts and avoidcommon pitfalls.
xix
xx Preface
• To make it easier to follow the relationships among features and concepts,we provide extensive forward and backward cross-references.
• We have provided sidebar discussions that focus on important concepts andsupply additional explanations for topics that programmers new to C++ of-ten find most difficult.
• Learning any programming language requires writing programs. To thatend, the primer provides extensive examples throughout the text. Sourcecode for the extended examples is available on the Web at the following URL:
http://www.awprofessional.com/cpp_primer
What hasn’t changed from earlier versions is that the book remains a compre-hensive tutorial introduction to C++. Our intent is to provide a clear, completeand correct guide to the language. We teach the language by presenting a series ofexamples, which, in addition to explaining language features, show how to makethe best use of C++. Although knowledge of C (the language on which C++ wasoriginally based) is not assumed, we do assume the reader has programmed in amodern block-structured language.
Structure of This Book
C++ Primer provides an introduction to the International Standard on C++, cover-ing both the language proper and the extensive library that is part of that standard.Much of the power of C++ comes from its support for programming with abstrac-tions. Learning to program effectively in C++ requires more than learning newsyntax and semantics. Our focus is on how to use the features of C++ to write pro-grams that are safe, that can be built quickly, and yet offer performance comparableto the sorts of low-level programs often written in C.
C++ is a large language and can be daunting to new users. Modern C++ can bethought of as comprising three parts:
• The low-level language, largely inherited from C
• More advanced language features that allow us to define our own data typesand to organize large-scale programs and systems
• The standard library, which uses these advanced features to provide a set ofuseful data structures and algorithms
Most texts present C++ in this same order: They start by covering the low-leveldetails and then introduce the the more advanced language features. They explainthe standard library only after having covered the entire language. The result, alltoo often, is that readers get bogged down in issues of low-level programming orthe complexities of writing type definitions and never really understand the powerof programming in a more abstract way. Needless to say, readers also often do notlearn enough to build their own abstractions.
In this edition we take a completely different tack. We start by covering thebasics of the language and the library together. Doing so allows you, the reader, to
Preface xxi
write significant programs. Only after a thorough grounding in using the library—and writing the kinds of abstract programs that the libary allows—do we move onto those features of C++ that will enable you to write your own abstractions.
Parts I and II cover the basic language and library facilities. The focus of theseparts is to learn how to write C++ programs and how to use the abstractions fromthe library. Most C++ programmers need to know essentially everything coveredin this portion of the book.
In addition to teaching the basics of C++, the material in Parts I and II serves an-other important purpose. The library facilities are themselves abstract data typeswritten in C++. The library can be defined using the same class-construction fea-tures that are available to any C++ programmer. Our experience in teaching C++ isthat by first using well-designed abstract types, readers find it easier to understandhow to build their own types.
Parts III through V focus on how we can write our own types. Part III intro-duces the heart of C++: its support for classes. The class mechanism providesthe basis for writing our own abstractions. Classes are also the foundation forobject-oriented and generic programming, which we cover in Part IV. The Primerconcludes with Part V, which covers advanced features that are of most use instructuring large, complex systems.
Acknowledgments
As in previous editions of this Primer, we’d like to extend our thanks to BjarneStroustrup for his tireless work on C++ and for his friendship to these authorsthroughout most of that time. We’d also like to thank Alex Stepanov for his originalinsights that led to the containers and algorithms that form the core of the standardlibrary. Finally, our thanks go to the C++ Standards committee members for theirhard work in clarifying, refining, and improving C++ over many years.
We also extend our deep-felt thanks to our reviewers, whose helpful commentson multiple drafts led us to make improvements great and small throughout thebook: Paul Abrahams, Michael Ball, Mary Dageforde, Paul DuBois, Matt Green-wood, Matthew P. Johnson, Andrew Koenig, Nevin Liber, Bill Locke, Robert Mur-ray, Phil Romanik, Justin Shaw, Victor Shtern, Clovis Tondo, Daveed Vandevoorde,and Steve Vinoski.
This book was typeset using LATEX and the many packages that accompany theLATEX distribution. Our well-justified thanks go to the members of the LATEX com-munity, who have made available such powerful typesetting tools.
The examples in this book have been compiled on the GNU and Microsoft com-pilers. Our thanks to their developers, and to those who have developed all theother C++ compilers, thereby making C++ a reality.
Finally, we thank the fine folks at Addison-Wesley who have shepherded thisedition through the publishing process: Debbie Lafferty, our original editor, whoinitiated this edition and who had been with the Primer from its very first edition;Peter Gordon, our new editor, whose insistence on updating and streamlining thetext have, we hope, greatly improved the presentation; Kim Boedigheimer, whokeeps us all on schedule; and Tyrrell Albaugh, Jim Markham, Elizabeth Ryan, andJohn Fuller, who saw us through the design and production process.
C H A P T E R 1G E T T I N G S T A R T E D
CONTENTS
Section 1.1 Writing a Simple C++ Program . . . . . . . 2Section 1.2 A First Look at Input/Output . . . . . . . . 5Section 1.3 A Word About Comments . . . . . . . . . . 10Section 1.4 Control Structures . . . . . . . . . . . . . . 11Section 1.5 Introducing Classes . . . . . . . . . . . . . 20Section 1.6 The C++ Program . . . . . . . . . . . . . . . 25Chapter Summary . . . . . . . . . . . . . . . . . . . . . . 28Defined Terms . . . . . . . . . . . . . . . . . . . . . . . . . 28
This chapter introduces most of the basic elements of C++: built-in,library, and class types; variables; expressions; statements; and func-tions. Along the way, we’ll briefly explain how to compile and exe-cute a program.
Having read this chapter and worked through the exercises, thereader should be able to write, compile, and execute simple pro-grams. Subsequent chapters will explain in more detail the topicsintroduced here.
1
2 Getting Started
Learning a new programming language requires writing programs. In thischapter, we’ll write a program to solve a simple problem that represents a com-mon data-processing task: A bookstore keeps a file of transactions, each of whichrecords the sale of a given book. Each transaction contains an ISBN (InternationalStandard Book Number, a unique identifier assigned to most books publishedthroughout the world), the number of copies sold, and the price at which eachcopy was sold. Each transaction looks like
0-201-70353-X 4 24.99
where the first element is the ISBN, the second is the number of books sold, and thelast is the sales price. Periodically the bookstore owner reads this file and computesthe number of copies of each title sold, the total revenue from that book, and theaverage sales price. We want to supply a program do these computations.
Before we can write this program we need to know some basic features of C++.At a minimum we’ll need to know how to write, compile, and execute a simpleprogram. What must this program do? Although we have not yet designed oursolution, we know that the program must
• Define variables
• Do input and output
• Define a data structure to hold the data we’re managing
• Test whether two records have the same ISBN
• Write a loop that will process every record in the transaction file
We’ll start by reviewing these parts of C++ and then write a solution to our book-store problem.
1.1 Writing a Simple C++ ProgramEvery C++ program contains one or more functions, one of which must be namedmain. A function consists of a sequence of statements that perform the work of thefunction. The operating system executes a program by calling the function namedmain. That function executes its constituent statements and returns a value to theoperating system.
Here is a simple version of main does nothing but return a value:
int main(){
return 0;}
The operating system uses the value returned by main to determine whether theprogram succeeded or failed. A return value of 0 indicates success.
The main function is special in various ways, the most important of which arethat the function must exist in every C++ program and it is the (only) function thatthe operating system explicitly calls.
Section 1.1 Writing a Simple C++ Program 3
We define main the same way we define other functions. A function definitionspecifies four elements: the return type, the function name, a (possibly empty)parameter list enclosed in parentheses, and the function body. The main functionmay have only a restricted set of parameters. As defined here, the parameter listis empty; Section 7.2.6 (p. 243) will cover the other parameters that can be definedfor main.
The main function is required to have a return type of int, which is the typethat represents integers. The int type is a built-in type, which means that thetype is defined by the language.
The final part of a function definition, the function body, is a block of statementsstarting with an open curly brace and ending with a close curly:
{return 0;
}
The only statement in our program is a return, which is a statement that termi-nates a function.
Note the semicolon at the end of the return statement. Semicolonsmark the end of most statements in C++. They are easy to overlook,but when forgotten can lead to mysterious compiler error messages.
When the return includes a value such as 0, that value is the return value ofthe function. The value returned must have the same type as the return type of thefunction or be a type that can be converted to that type. In the case of main thereturn type must be int, and the value 0 is an int.
On most systems, the return value from main is a status indicator. A returnvalue of 0 indicates the successful completion of main. Any other return valuehas a meaning that is defined by the operating system. Usually a nonzero returnindicates that an error occurred. Each operating system has its own way of tellingthe user what main returned.
1.1.1 Compiling and Executing Our ProgramHaving written the program, we need to compile it. How you compile a programdepends on your operating system and compiler. For details on how your particu-lar compiler works, you’ll need to check the reference manual or ask a knowledge-able colleague.
Many PC-based compilers are run from an integrated development environ-ment (IDE) that bundles the compiler with associated build and analysis tools.These environments can be a great asset in developing complex programs but re-quire a fair bit of time to learn how to use effectively. Most of these environmentsinclude a point-and-click interface that allows the programmer to write a programand use various menus to compile and execute the program. Learning how to usesuch environments is well beyond the scope of this book.
Most compilers, including those that come with an IDE, provide a command-line interface. Unless you are already familiar with using your compiler’s IDE,
4 Getting Started
it can be easier to start by using the simpler, command-line interface. Using thecommand-line interface lets you avoid the overhead of learning the IDE beforelearning the language.
Program Source File Naming Convention
Whether we are using a command-line interface or an IDE, most compilers expectthat the program we want to compile will be stored in a file. Program files arereferred to as source files. On most systems, a source file has a name that consistsof two parts: a file name—for example, prog1—and a file suffix. By convention,the suffix indicates that the file is a program. The suffix often also indicates whatlanguage the program is written in and selects which compiler to run. The systemthat we used to compile the examples in this book treats a file with a suffix of .ccas a C++ program and so we stored this program as
prog1.cc
The suffix for C++ program files depends on which compiler you’re running. Otherconventions include
prog1.cxxprog1.cppprog1.cpprog1.C
INVOKING THE GNU OR MICROSOFT COMPILERS
The command used to invoke the C++ compiler varies across compilers and operatingsystems. The most common compilers are the GNU compiler and the Microsoft VisualStudio compilers. By default the command to invoke the GNU compiler is g++:
$ g++ prog1.cc -o prog1
where $ is the system prompt. This command generates an executable file namedprog1 or prog1.exe, depending on the operating system. On UNIX, executable fileshave no suffix; on Windows, the suffix is .exe. The -o prog1 is an argument to thecompiler and names the file in which to put the executable file. If the -o prog1 isomitted, then the compiler generates an executable named a.out on UNIX systemsand a.exe on Windows.
The Microsoft compilers are invoked using the command cl:
C:\directory> cl -GX prog1.cpp
where C:directory> is the system prompt and directory is the name of the cur-rent directory. The command to invoke the compiler is cl, and -GX is an option thatis required for programs compiled using the command-line interface. The Microsoftcompiler automatically generates an executable with a name that corresponds to thesource file name. The executable has the suffix .exe and the same name as the sourcefile name. In this case, the executable is named prog1.exe.
For further information consult your compiler’s user’s guide.
Section 1.2 A First Look at Input/Output 5
Running the Compiler from the Command Line
If we are using a command-line interface, we will typically compile a program ina console window (such as a shell window on a UNIX system or a CommandPrompt window on Windows). Assuming that our main program is in a filenamed prog1.cc, we might compile it by using a command such as:
$ CC prog1.cc
where CC names the compiler and $ represents the system prompt. The output ofthe compiler is an executable file that we invoke by naming it. On our system, thecompiler generates the executable in a file named a.exe. UNIX compilers tend toput their executables in a file named a.out. To run an executable we supply thatname at the command-line prompt:
$ a.exe
executes the program we compiled. On UNIX systems you sometimes must alsospecify which directory the file is in, even if it is in the current directory. In suchcases, we would write
$ ./a.exe
The “.” followed by a slash indicates that the file is in the current directory.The value returned from main is accessed in a system-dependent manner. On
both UNIX and Windows systems, after executing the program, you must issue anappropriate echo command. On UNIX systems, we obtain the status by writing
$ echo $?
To see the status on a Windows system, we write
C:\directory> echo %ERRORLEVEL%
EXE R C I S E S SE C TI ON 1.1.1
Exercise 1.1: Review the documentation for your compiler and determine what filenaming convention it uses. Compile and run the main program from page 2.
Exercise 1.2: Change the program to return -1. A return value of -1 is often treatedas an indicator that the program failed. However, systems vary as to how (or evenwhether) they report a failure from main. Recompile and rerun your program to seehow your system treats a failure indicator from main.
1.2 A First Look at Input/OutputC++ does not directly define any statements to do input or output (IO). Instead, IOis provided by the standard library. The IO library provides an extensive set of
6 Getting Started
facilities. However, for many purposes, including the examples in this book, oneneeds to know only a few basic concepts and operations.
Most of the examples in this book use the iostream library, which handlesformatted input and output. Fundamental to the iostream library are two typesnamed istream and ostream, which represent input and output streams, respec-tively. A stream is a sequence of characters intended to be read from or written toan IO device of some kind. The term “stream” is intended to suggest that the char-acters are generated, or consumed, sequentially over time.
1.2.1 Standard Input and Output ObjectsThe library defines four IO objects. To handle input, we use an object of typeistream named cin (pronounced “see-in”). This object is also referred to as thestandard input. For output, we use an ostream object named cout (pronounced“see-out”). It is often referred to as the standard output. The library also definestwo other ostream objects, named cerr and clog (pronounced “see-err” and“see-log,” respectively). The cerr object, referred to as the standard error, is typi-cally used to generate warning and error messages to users of our programs. Theclog object is used for general information about the execution of the program.
Ordinarily, the system associates each of these objects with the window inwhich the program is executed. So, when we read from cin, data is read from thewindow in which the program is executing, and when we write to cout, cerr, orclog, the output is written to the same window. Most operating systems give usa way of redirecting the input or output streams when we run a program. Usingredirection we can associate these streams with files of our choosing.
1.2.2 A Program that Uses the IO LibrarySo far, we have seen how to compile and execute a simple program, although thatprogram did no work. In our overall problem, we’ll have several records thatrefer to the same ISBN. We’ll need to consolidate those records into a single total,implying that we’ll need to know how to add the quantities of books sold.
To see how to solve part of that problem, let’s start by looking at how we mightadd two numbers. Using the IO library, we can extend our main program to askthe user to give us two numbers and then print their sum:
#include <iostream>int main(){
std::cout << "Enter two numbers:" << std::endl;
int v1, v2;std::cin >> v1 >> v2;
std::cout << "The sum of " << v1 << " and " << v2<< " is " << v1 + v2 << std::endl;
return 0;}
Section 1.2 A First Look at Input/Output 7
This program starts by printing
Enter two numbers:
on the user’s screen and then waits for input from the user. If the user enters
3 7
followed by a newline, then the program produces the following output:
The sum of 3 and 7 is 10
The first line of our program is a preprocessor directive:
#include <iostream>
which tells the compiler that we want to use the iostream library. The nameinside angle brackets is a header. Every program that uses a library facility mustinclude its associated header. The #include directive must be written on a singleline—the name of the header and the #include must appear on the same line. Ingeneral, #include directives should appear outside any function. Typically, allthe #include directives for a program appear at the beginning of the file.
Writing to a Stream
The first statement in the body of main executes an expression. In C++ an ex-pression is composed of one or more operands and (usually) an operator. Theexpressions in this statement use the output operator (the << operator) to print theprompt on the standard output:
std::cout << "Enter two numbers:" << std::endl;
This statement uses the output operator twice. Each instance of the output oper-ator takes two operands: The left-hand operand must be an ostream object; theright-hand operand is a value to print. The operator writes its right-hand operandto the ostream that is its left-hand operand.
In C++ every expression produces a result, which typically is the value gener-ated by applying an operator to its operands. In the case of the output operator,the result is the value of its left-hand operand. That is, the value returned by anoutput operation is the output stream itself.
The fact that the operator returns its left-hand operand allows us to chain to-gether output requests. The statement that prints our prompt is equivalent to
(std::cout << "Enter two numbers:") << std::endl;
Because (std::cout << "Enter two numbers:") returns its left operand,std::cout, this statement is equivalent to
std::cout << "Enter two numbers:";std::cout << std::endl;
8 Getting Started
endl is a special value, called a manipulator, that when written to an outputstream has the effect of writing a newline to the output and flushing the bufferassociated with that device. By flushing the buffer, we ensure that the user will seethe output written to the stream immediately.
Programmers often insert print statements during debugging. Suchstatements should always flush the stream. Forgetting to do so maycause output to be left in the buffer if the program crashes, leading toincorrect inferences about where the program crashed.
Using Names from the Standard Library
Careful readers will note that this program uses std::cout and std::endlrather than just cout and endl. The prefix std:: indicates that the names coutand endl are defined inside the namespace named std. Namespaces allow pro-grammers to avoid inadvertent collisions with the same names defined by a library.Because the names that the standard library defines are defined in a namespace,we can use the same names for our own purposes.
One side effect of the library’s use of a namespace is that when we use a namefrom the library, we must say explicitly that we want to use the name from the stdnamespace. Writing std::cout uses the scope operator (the :: operator) to saythat we want to use the name cout that is defined in the namespace std. We’ll seein Section 3.1 (p. 78) a way that programs often use to avoid this verbose syntax.
Reading From a Stream
Having written our prompt, we next want to read what the user writes. We startby defining two variables named v1 and v2 to hold the input:
int v1, v2;
We define these variables as type int, which is the built-in type representing in-tegral values. These variables are uninitialized, meaning that we gave them noinitial value. Our first use of these variables will be to read a value into them, sothe fact that they have no initial value is okay.
The next statement
std::cin >> v1 >> v2;
reads the input. The input operator (the >> operator) behaves analogously to theoutput operator. It takes an istream as its left-hand operand and an object as itsright-hand operand. It reads from its istream operand and stores the value it readin its right-hand operand. Like the output operator, the input operator returns itsleft-hand operand as its result. Because the operator returns its left-hand operand,we can combine a sequence of input requests into a single statement. In otherwords, this input operation is equivalent to
std::cin >> v1;std::cin >> v2;
Section 1.2 A First Look at Input/Output 9
The effect of our input operation is to read two values from the standard input,storing the first in v1 and the second in v2.
Completing the Program
What remains is to print our result:
std::cout << "The sum of " << v1 << " and " << v2<< " is " << v1 + v2 << std::endl;
This statement, although it is longer than the statement that printed the prompt,is conceptually no different. It prints each of its operands to the standard output.What is interesting is that the operands are not all the same kinds of values. Someoperands are string literals, such as
"The sum of "
and others are various int values, such as v1, v2, and the result of evaluating thearithmetic expression:
v1 + v2
The iostream library defines versions of the input and output operators that ac-cept all of the built-in types.
When writing a C++ program, in most places that a space appears wecould instead use a newline. One exception to this rule is that spacesinside a string literal cannot be replaced by a newline. Another excep-tion is that spaces are not allowed inside preprocessor directives.
KEY CONCEPT: INITIALIZED AND UNINITIALIZED VARIABLES
Initialization is an important concept in C++ and one to which we will return through-out this book.
Initialized variables are those that are given a value when they are defined. Unini-tialized variables are not given an initial value:
int val1 = 0; // initializedint val2; // uninitialized
It is almost always right to give a variable an initial value, but we are not required todo so. When we are certain that the first use of a variable gives it a new value, thenthere is no need to invent an initial value. For example, our first nontrivial programon page 6 defined uninitialized variables into which we immediately read values.
When we define a variable, we should give it an initial value unless we are certainthat the initial value will be overwritten before the variable is used for any otherpurpose. If we cannot guarantee that the variable will be reset before being read, weshould initialize it.
10 Getting Started
EXE R C I S E S SE C TI ON 1.2.2
Exercise 1.3: Write a program to print “Hello, World” on the standard output.
Exercise 1.4: Our program used the built-in addition operator, +, to generate the sumof two numbers. Write a program that uses the multiplication operator, *, to generatethe product of two numbers.
Exercise 1.5: We wrote the output in one large statement. Rewrite the program to usea separate statement to print each operand.
Exercise 1.6: Explain what the following program fragment does:
std::cout << "The sum of " << v1;<< " and " << v2;<< " is " << v1 + v2<< std::endl;
Is this code legal? If so, why? If not, why not?
1.3 A Word About CommentsBefore our programs get much more complicated, we should see how C++ handlescomments. Comments help the human readers of our programs. They are typicallyused to summarize an algorithm, identify the purpose of a variable, or clarify anotherwise obscure segment of code. Comments do not increase the size of theexecutable program. The compiler ignores all comments.
In this book, we italicize comments to make them stand out from thenormal program text. In actual programs, whether comment text isdistinguished from the text used for program code depends on the so-phistication of the programming environment.
There are two kinds of comments in C++: single-line and paired. A single-linecomment starts with a double slash (//). Everything to the right of the slashes onthe current line is a comment and ignored by the compiler.
The other delimiter, the comment pair (/* */), is inherited from the C language.Such comments begin with a /* and end with the next */. The compiler treatseverything that falls between the /* and */ as part of the comment:
#include <iostream>
/* Simple main function: Read two numbers and write their sum */int main(){
// prompt user to enter two numbersstd::cout << "Enter two numbers:" << std::endl;
int v1, v2; // uninitializedstd::cin >> v1 >> v2; // read inputreturn 0;
}
Section 1.4 Control Structures 11
A comment pair can be placed anywhere a tab, space, or newline is permitted.Comment pairs can span multiple lines of a program but are not required to do so.When a comment pair does span multiple lines, it is often a good idea to indicatevisually that the inner lines are part of a multi-line comment. Our style is to begineach line in the comment with an asterisk, thus indicating that the entire range ispart of a multi-line comment.
Programs typically contain a mixture of both comment forms. Comment pairsgenerally are used for multi-line explanations, whereas double slash commentstend to be used for half-line and single-line remarks.
Too many comments intermixed with the program code can obscure the code.It is usually best to place a comment block above the code it explains.
Comments should be kept up to date as the code itself changes. Programmersexpect comments to remain accurate and so believe them, even when other formsof system documentation are known to be out of date. An incorrect comment isworse than no comment at all because it may mislead a subsequent reader.
Comment Pairs Do Not Nest
A comment that begins with /* always ends with the next */. As a result, onecomment pair cannot occur within another. The compiler error message(s) thatresult from this kind of program mistake can be mysterious and confusing. As anexample, compile the following program on your system:
#include <iostream>
/** comment pairs /* */ cannot nest.* ‘‘cannot nest’’ is considered source code,* as is the rest of the program*/
int main(){
return 0;}
When commenting out a large section of a program, it can seem easiest to puta comment pair around a region that you want to omit temporarily. The troubleis that if that code already has a comment pair, then the newly inserted commentwill terminate prematurely. A better way to temporarily ignore a section of codeis to use your editor to insert single-line comment at the beginning of each line ofcode you want to ignore. That way, you need not worry about whether the codeyou are commenting out already contains a comment pair.
1.4 Control StructuresStatements execute sequentially: The first statement in a function is executed first,followed by the second, and so on. Of course, few programs—including the onewe’ll need to write to solve our bookstore problem—can be written using onlysequential execution. Instead, programming languages provide various control
12 Getting Started
EXE R C I S E S SE C TI ON 1.3
Exercise 1.7: Compile a program that has incorrectly nested comments.
Exercise 1.8: Indicate which, if any, of the following output statements, are legal.
std::cout << "/*";std::cout << "*/";std::cout << /* "*/" */;
After you’ve predicted what will happen, test your answer by compiling a programwith these three statements. Correct any errors you encounter.
structures that allow for more complicated execution paths. This section will takea brief look at some of the control structures provided by C++. Chapter 6 coversstatements in detail.
1.4.1 The while StatementA while statement provides for iterative execution. We could use a while towrite a program to sum the numbers from 1 through 10 inclusive as follows:
#include <iostream>
int main(){
int sum = 0, val = 1;// keep executing the while until val is greater than 10while (val <= 10) {
sum += val; // assigns sum + val to sum++val; // add 1 to val
}std::cout << "Sum of 1 to 10 inclusive is "
<< sum << std::endl;
return 0;}
This program when compiled and executed will print:
Sum of 1 to 10 inclusive is 55
As before, we begin by including the iostream header and define a mainfunction. Inside main we define two int variables: sum, which will hold oursummation, and val, which will represent each of the values from 1 through 10.We give sum an initial value of zero and start val off with the value one.
The important part is the while statement. A while has the form
while (condition) while_body_statement;
A while executes by (repeatedly) testing the condition and executing the associ-ated while_body_statement until the condition is false.
Section 1.4 Control Structures 13
A condition is an expression that is evaluated so that its result can be tested. Ifthe resulting value is nonzero, then the condition is true; if the value is zero thenthe condition is false.
If the condition is true (the expression evaluates to a value other than zero) thenwhile_body_statement is executed. After executing while_body_statement, the condi-tion is tested again. If condition remains true, then the while_body_statement is againexecuted. The while continues, alternatively testing the condition and executingwhile_body_statement until the condition is false.
In this program, the while statement is:
// keep executing the while until val is greater than 10while (val <= 10) {
sum += val; // assigns sum + val to sum++val; // add 1 to val
}
The condition in the while uses the less-than-or-equal operator (the <= operator)to compare the current value of val and 10. As long as val is less than or equalto 10, we execute the body of the while. In this case, the body of the while is ablock containing two statements:
{sum += val; // assigns sum + val to sum++val; // add 1 to val
}
A block is a sequence of statements enclosed by curly braces. In C++, a block maybe used wherever a statement is expected. The first statement in the block uses thecompound assignment operator, (the += operator). This operator adds its right-hand operand to its left-hand operand. It has the same effect as writing an additionand an assignment:
sum = sum + val; // assign sum + val to sum
Thus, the first statement adds the value of val to the current value of sum andstores the result back into sum.
The next statement
++val; // add 1 to val
uses the prefix increment operator (the ++ operator). The increment operator addsone to its operand. Writing ++val is the same as writing val = val + 1.
After executing the while body we again execute the condition in the while.If the (now incremented) value of val is still less than or equal to 10, then thebody of the while is executed again. The loop continues, testing the conditionand executing the body, until val is no longer less than or equal to 10.
Once val is greater than 10, we fall out of the while loop and execute thestatement following the while. In this case, that statement prints our output,followed by the return, which completes our main program.
14 Getting Started
KEY CONCEPT: INDENTATION AND FORMATTING OF C++ PROGRAMS
C++ programs are largely free-format, meaning that the positioning of curly braces,indentation, comments, and newlines usually has no effect on the meaning of ourprograms. For example, the curly brace that denotes the beginning of the body of maincould be on the same line as main, positioned as we have done, at the beginning of thenext line, or placed anywhere we’d like. The only requirement is that it be the firstnonblank, noncomment character that the compiler sees after the close parenthesisthat concludes main’s parameter list.
Although we are largely free to format programs as we wish, the choices we makeaffect the readability of our programs. We could, for example, have written main on asingle, long line. Such a definition, although legal, would be hard to read.
Endless debates occur as to the right way to format C or C++ programs. Our beliefis that there is no single correct style but that there is value in consistency. We tendto put the curly braces that delimit functions on their own lines. We tend to indentcompound input or output expressions so that the operators line up, as we did withthe statement that wrote the output in the main function on page 6. Other indentationconventions will become clear as our programs become more complex.
The important thing to keep in mind is that other ways to format programs arepossible. When choosing a formatting style, think about how it affects readabilityand comprehension. Once you’ve chosen a style, use it consistently.
1.4.2 The for StatementIn our while loop, we used the variable val to control how many times we it-erated through the loop. On each pass through the while, the value of val wastested and then in the body the value of val was incremented.
The use of a variable like val to control a loop happens so often that the lan-guage defines a second control structure, called a for statement, that abbreviatesthe code that manages the loop variable. We could rewrite the program to sum thenumbers from 1 through 10 using a for loop as follows:
#include <iostream>
int main(){
int sum = 0;
// sum values from 1 up to 10 inclusivefor (int val = 1; val <= 10; ++val)
sum += val; // equivalent to sum = sum + val
std::cout << "Sum of 1 to 10 inclusive is "<< sum << std::endl;
return 0;}
Prior to the for loop, we define sum, which we set to zero. The variable val isused only inside the iteration and is defined as part of the for statement itself. Thefor statement
Section 1.4 Control Structures 15
for (int val = 1; val <= 10; ++val)sum += val; // equivalent to sum = sum + val
has two parts: the for header and the for body. The header controls how oftenthe body is executed. The header itself consists of three parts: an init-statement, acondition, and an expression. In this case, the init-statement
int val = 1;
defines an int object named val and gives it an initial value of one. The init-statement is performed only once, on entry to the for. The condition
val <= 10
which compares the current value in val to 10, is tested each time through theloop. As long as val is less than or equal to 10, we execute the for body. Onlyafter executing the body is the expression executed. In this for, the expression usesthe prefix increment operator, which as we know adds one to the value of val.After executing the expression, the for retests the condition. If the new value ofval is still less than or equal to 10, then the for loop body is executed and val isincremented again. Execution continues until the condition fails.
In this loop, the for body performs the summation
sum += val; // equivalent to sum = sum + val
The body uses the compound assignment operator to add the current value of valto sum, storing the result back into sum.
To recap, the overall execution flow of this for is:
1. Create val and initialize it to 1.
2. Test whether val is less than or equal to 10.
3. If val is less than or equal to 10, execute the for body, which adds val tosum. If val is not less than or equal to 10, then break out of the loop andcontinue execution with the first statement following the for body.
4. Increment val.
5. Repeat the test in step 2, continuing with the remaining steps as long as thecondition is true.
When we exit the for loop, the variable val is no longer accessible. Itis not possible to use val after this loop terminates. However, not allcompilers enforce this requirement.
In pre-Standard C++ names defined in a for header were accessibleoutside the for itself. This change in the language definition can sur-prise people accustomed to using an older compiler when they insteaduse a compiler that adheres to the standard.
16 Getting Started
COMPILATION REVISITED
Part of the compiler’s job is to look for errors in the program text. A compiler cannotdetect whether the meaning of a program is correct, but it can detect errors in the formof the program. The following are the most common kinds of errors a compiler willdetect.
1. Syntax errors. The programmer has made a grammatical error in the C++ lan-guage. The following program illustrates common syntax errors; each commentdescribes the error on the following line:
// error: missing ’)’ in parameter list for mainint main ( {
// error: used colon, not a semicolon after endlstd::cout << "Read each file." << std::endl:
// error: missing quotes around string literalstd::cout << Update master. << std::endl;
// ok: no errors on this linestd::cout << "Write new master." << std::endl;
// error: missing ’;’ on return statementreturn 0
}
2. Type errors. Each item of data in C++ has an associated type. The value 10,for example, is an integer. The word “hello” surrounded by double quotationmarks is a string literal. One example of a type error is passing a string literalto a function that expects an integer argument.
3. Declaration errors. Every name used in a C++ program must be declared beforeit is used. Failure to declare a name usually results in an error message. Thetwo most common declaration errors are to forget to use std:: when accessinga name from the library or to inadvertently misspell the name of an identifier:
#include <iostream>
int main(){
int v1, v2;std::cin >> v >> v2; // error: uses "v" not "v1"
// cout not defined, should be std::coutcout << v1 + v2 << std::endl;return 0;
}
An error message contains a line number and a brief description of what the com-piler believes we have done wrong. It is a good practice to correct errors in the se-quence they are reported. Often a single error can have a cascading effect and causea compiler to report more errors than actually are present. It is also a good idea torecompile the code after each fix—or after making at most a small number of obviousfixes. This cycle is known as edit-compile-debug.
Section 1.4 Control Structures 17
EXE R C I S E S SE C TI ON 1.4.2
Exercise 1.9: What does the following for loop do? What is the final value of sum?
int sum = 0;for (int i = -100; i <= 100; ++i)
sum += i;
Exercise 1.10: Write a program that uses a for loop to sum the numbers from 50 to100. Now rewrite the program using a while.
Exercise 1.11: Write a program using a while loop to print the numbers from 10down to 0. Now rewrite the program using a for.
Exercise 1.12: Compare and contrast the loops you wrote in the previous two exer-cises. Are there advantages or disadvantages to using either form?
Exercise 1.13: Compilers vary as to how easy it is to understand their diagnostics.Write programs that contain the common errors discussed in the box on 16. Studythe messages the compiler generates so that these messages will be familiar when youencounter them while compiling more complex programs.
1.4.3 The if StatementA logical extension of summing the values between 1 and 10 is to sum the valuesbetween two numbers our user supplies. We might use the numbers directly in ourfor loop, using the first input as the lower bound for the range and the secondas the upper bound. However, if the user gives us the higher number first, thatstrategy would fail: Our program would exit the for loop immediately. Instead,we should adjust the range so that the larger number is the upper bound and thesmaller is the lower. To do so, we need a way to see which number is larger.
Like most languages, C++ provides an if statement that supports conditionalexecution. We can use an if to write our revised sum program:
#include <iostream>
int main(){
std::cout << "Enter two numbers:" << std::endl;int v1, v2;std::cin >> v1 >> v2; // read input
// use smaller number as lower bound for summation// and larger number as upper boundint lower, upper;if (v1 <= v2) {
lower = v1;upper = v2;
} else {lower = v2;upper = v1;
}
18 Getting Started
int sum = 0;
// sum values from lower up to and including upperfor (int val = lower; val <= upper; ++val)
sum += val; // sum = sum + val
std::cout << "Sum of " << lower<< " to " << upper<< " inclusive is "<< sum << std::endl;
return 0;}
If we compile and execute this program and give it as input the numbers 7 and 3,then the output of our program will be
Sum of 3 to 7 inclusive is 25
Most of the code in this program should already be familiar from our earlierexamples. The program starts by writing a prompt to the user and defines fourint variables. It then reads from the standard input into v1 and v2. The only newcode is the if statement
// use smaller number as lower bound for summation// and larger number as upper boundint lower, upper;if (v1 <= v2) {
lower = v1;upper = v2;
} else {lower = v2;upper = v1;
}
The effect of this code is to set upper and lower appropriately. The if conditiontests whether v1 is less than or equal to v2. If so, we perform the block that imme-diately follows the condition. This block contains two statements, each of whichdoes an assignment. The first statement assigns v1 to lower and the second as-signs v2 to upper.
If the condition is false—that is, if v1 is larger than v2—then we execute thestatement following the else. Again, this statement is a block consisting of twoassignments. We assign v2 to lower and v1 to upper.
1.4.4 Reading an Unknown Number of InputsAnother change we might make to our summation program on page 12 would beto allow the user to specify a set of numbers to sum. In this case we can’t know howmany numbers we’ll be asked to add. Instead, we want to keep reading numbersuntil the program reaches the end of the input. When the input is finished, theprogram writes the total to the standard output:
Section 1.4 Control Structures 19
EXE R C I S E S SE C TI ON 1.4.3
Exercise 1.14: What happens in the program presented in this section if the input val-ues are equal?
Exercise 1.15: Compile and run the program from this section with two equal valuesas input. Compare the output to what you predicted in the previous exercise. Explainany discrepancy between what happened and what you predicted.
Exercise 1.16: Write a program to print the larger of two inputs supplied by the user.
Exercise 1.17: Write a program to ask the user to enter a series of numbers. Print amessage saying how many of the numbers are negative numbers.
#include <iostream>
int main(){
int sum = 0, value;// read till end-of-file, calculating a running total of all values readwhile (std::cin >> value)
sum += value; // equivalent to sum = sum + valuestd::cout << "Sum is: " << sum << std::endl;
return 0;}
If we give this program the input
3 4 5 6
then our output will be
Sum is: 18
As usual, we begin by including the necessary headers. The first line insidemain defines two int variables, named sum and value. We’ll use value to holdeach number we read, which we do inside the condition in the while:
while (std::cin >> value)
What happens here is that to evaluate the condition, the input operation
std::cin >> value
is executed, which has the effect of reading the next number from the standardinput, storing what was read in value. The input operator (Section 1.2.2, p. 8)returns its left operand. The condition tests that result, meaning it tests std::cin.
When we use an istream as a condition, the effect is to test the state of thestream. If the stream is valid—that is, if it is still possible to read another input—then the test succeeds. An istream becomes invalid when we hit end-of-file orencounter an invalid input, such as reading a value that is not an integer. Anistream that is in an invalid state will cause the condition to fail.
20 Getting Started
Until we do encounter end-of-file (or some other input error), the test will suc-ceed and we’ll execute the body of the while. That body is a single statementthat uses the compound assignment operator. This operator adds its right-handoperand into the left hand operand.
ENTERING AN END-OF-FILE FROM THE KEYBOARD
Operating systems use different values for end-of-file. On Windows systems we enteran end-of-file by typing a control-z—simultaneously type the “ctrl” key and a “z.” OnUNIX systems, including Mac OS-X machines, it is usually control-d.
Once the test fails, the while terminates and we fall through and execute thestatement following the while. That statement prints sum followed by endl,which prints a newline and flushes the buffer associated with cout. Finally, weexecute the return, which as usual returns zero to indicate success.
EXE R C I S E S SE C TI ON 1.4.4
Exercise 1.18: Write a program that prompts the user for two numbers and writeseach number in the range specified by the two numbers to the standard output.
Exercise 1.19: What happens if you give the numbers 1000 and 2000 to the programwritten for the previous exercise? Revise the program so that it never prints more than10 numbers per line.
Exercise 1.20: Write a program to sum the numbers in a user-specified range, omittingthe if test that sets the upper and lower bounds. Predict what happens if the input isthe numbers 7 and 3, in that order. Now run the program giving it the numbers 7 and3, and see if the results match your expectation. If not, restudy the discussion on thefor and while loop until you understand what happened.
1.5 Introducing ClassesThe only remaining feature we need to understand before solving our bookstoreproblem is how to write a data structure to represent our transaction data. In C++we define our own data structure by defining a class. The class mechanism is oneof the most important features in C++. In fact, a primary focus of the design of C++is to make it possible to define class types that behave as naturally as the built-intypes themselves. The library types that we’ve seen already, such as istream andostream, are all defined as classes—that is, they are not strictly speaking part ofthe language.
Complete understanding of the class mechanism requires mastering a lot ofinformation. Fortunately, it is possible to use a class that someone else has writtenwithout knowing how to define a class ourselves. In this section, we’ll describe asimple class that we can use in solving our bookstore problem. We’ll implement
Section 1.5 Introducing Classes 21
this class in the subsequent chapters as we learn more about types, expressions,statements, and functions—all of which are used in defining classes.
To use a class we need to know three things:
1. What is its name?
2. Where is it defined?
3. What operations does it support?
For our bookstore problem, we’ll assume that the class is named Sales_item andthat it is defined in a header named Sales_item.h.
1.5.1 The Sales_item ClassThe purpose of the Sales_item class is to store an ISBN and keep track of thenumber of copies sold, the revenue, and average sales price for that book. Howthese data are stored or computed is not our concern. To use a class, we need notknow anything about how it is implemented. Instead, what we need to know iswhat operations the class provides.
As we’ve seen, when we use library facilities such as IO, we must include theassociated headers. Similarly, for our own classes, we must make the definitionsassociated with the class available to the compiler. We do so in much the sameway. Typically, we put the class definition into a file. Any program that wants touse our class must include that file.
Conventionally, class types are stored in a file with a name that, like the nameof a program source file, has two parts: a file name and a file suffix. Usually the filename is the same as the class defined in the header. The suffix usually is .h, butsome programmers use .H, .hpp, or .hxx. Compilers usually aren’t picky aboutheader file names, but IDEs sometimes are. We’ll assume that our class is definedin a file named Sales_item.h.
Operations on Sales_item Objects
Every class defines a type. The type name is the same as the name of the class.Hence, our Sales_item class defines a type named Sales_item. As with thebuilt-in types, we can define a variable of a class type. When we write
Sales_item item;
we are saying that item is an object of type Sales_item. We often contract thephrase “an object of type Sales_item” to “a Sales_item object” or even moresimply to “a Sales_item.”
In addition to being able to define variables of type Sales_item, we can per-form the following operations on Sales_item objects:
• Use the addition operator, +, to add two Sales_items
• Use the input operator, >>, to read a Sales_item object
22 Getting Started
• Use the output operator, <<, to write a Sales_item object
• Use the assignment operator, =, to assign one Sales_item object to another
• Call the same_isbn function to determine if two Sales_items refer to thesame book
Reading and Writing Sales_items
Now that we know the operations that the class provides, we can write some sim-ple programs to use this class. For example, the following program reads datafrom the standard input, uses that data to build a Sales_item object, and writesthat Sales_item object back onto the standard output:
#include <iostream>#include "Sales_item.h"
int main(){
Sales_item book;
// read ISBN, number of copies sold, and sales pricestd::cin >> book;
// write ISBN, number of copies sold, total revenue, and average pricestd::cout << book << std::endl;
return 0;}
If the input to this program is
0-201-70353-X 4 24.99
then the output will be
0-201-70353-X 4 99.96 24.99
Our input said that we sold four copies of the book at $24.99 each, and the outputindicates that the total sold was four, the total revenue was $99.96, and the averageprice per book was $24.99.
This program starts with two #include directives, one of which uses a newform. The iostream header is defined by the standard library; the Sales_itemheader is not. Sales_item is a type that we ourselves have defined. When weuse our own headers, we use quotation marks (" ") to surround the header name.
Headers for the standard library are enclosed in angle brackets (< >).Nonstandard headers are enclosed in double quotes (" ").
Inside main we start by defining an object, named book, which we’ll use tohold the data that we read from the standard input. The next statement reads intothat object, and the third statement prints it to the standard output followed asusual by printing endl to flush the buffer.
Section 1.5 Introducing Classes 23
KEY CONCEPT: CLASSES DEFINE BEHAVIOR
As we go through these programs that use Sales_items, the important thing to keepin mind is that the author of the Sales_item class defined all the actions that canbe performed by objects of this class. That is, the author of the Sales_item datastructure defines what happens when a Sales_item object is created and what hap-pens when the addition or the input and output operators are applied to Sales_itemobjects, and so on.
In general, only the operations defined by a class can be used on objects of the classtype. For now, the only operations we know we can peeform on Sales_item objectsare the ones listed on page 21.
We’ll see how these operations are defined in Sections 7.7.3 and 14.2.
Adding Sales_items
A slightly more interesting example adds two Sales_item objects:
#include <iostream>#include "Sales_item.h"
int main(){
Sales_item item1, item2;
std::cin >> item1 >> item2; // read a pair of transactionsstd::cout << item1 + item2 << std::endl; // print their sum
return 0;}
If we give this program the following input
0-201-78345-X 3 20.000-201-78345-X 2 25.00
our output is
0-201-78345-X 5 110 22
This program starts by including the Sales_item and iostream headers.Next we define two Sales_item objects to hold the two transactions that we wishto sum. The output expression does the addition and prints the result. We knowfrom the list of operations on page 21 that adding two Sales_items togethercreates a new object whose ISBN is that of its operands and whose number soldand revenue reflect the sum of the corresponding values in its operands. We alsoknow that the items we add must represent the same ISBN.
It’s worth noting how similar this program looks to the one on page 6: We readtwo inputs and write their sum. What makes it interesting is that instead of readingand printing the sum of two integers, we’re reading and printing the sum of twoSales_item objects. Moreover, the whole idea of “sum” is different. In the caseof ints we are generating a conventional sum—the result of adding two numericvalues. In the case of Sales_item objects we use a conceptually new meaning forsum—the result of adding the components of two Sales_item objects.
24 Getting Started
EXE R C I S E S SE C TI ON 1.5.1
Exercise 1.21: The Web site (http://www.awprofessional.com/cpp_primer)contains a copy of Sales_item.h in the Chapter 1 code directory. Copy that file toyour working directory. Write a program that loops through a set of book sales trans-actions, reading each transaction and writing that transaction to the standard output.
Exercise 1.22: Write a program that reads two Sales_item objects that have thesame ISBN and produces their sum.
Exercise 1.23: Write a program that reads several transactions for the same ISBN.Write the sum of all the transactions that were read.
1.5.2 A First Look at Member FunctionsUnfortunately, there is a problem with the program that adds Sales_items. Whatshould happen if the input referred to two different ISBNs? It doesn’t make senseto add the data for two different ISBNs together. To solve this problem, we’ll firstcheck whether the Sales_item operands refer to the same ISBNs:
#include <iostream>#include "Sales_item.h"
int main(){
Sales_item item1, item2;
std::cin >> item1 >> item2;// first check that item1 and item2 represent the same bookif (item1.same_isbn(item2)) {
std::cout << item1 + item2 << std::endl;return 0; // indicate success
} else {std::cerr << "Data must refer to same ISBN"
<< std::endl;return -1; // indicate failure
}}
The difference between this program and the previous one is the if test and itsassociated else branch. Before explaining the if condition, we know that whatthis program does depends on the condition in the if. If the test succeeds, thenwe write the same output as the previous program and return 0 indicating success.If the test fails, we execute the block following the else, which prints a messageand returns an error indicator.
What Is a Member Function?
The if condition
// first check that item1 and item2 represent the same bookif (item1.same_isbn(item2)) {
Section 1.6 The C++ Program 25
calls a member function of the Sales_item object named item1. A memberfunction is a function that is defined by a class. Member functions are sometimesreferred to as the methods of the class.
Member functions are defined once for the class but are treated as membersof each object. We refer to these operations as member functions because they(usually) operate on a specific object. In this sense, they are members of the object,even though a single definition is shared by all objects of the same type.
When we call a member function, we (usually) specify the object on which thefunction will operate. This syntax uses the dot operator (the “.” operator):
item1.same_isbn
means “the same_isbn member of the object named item1.” The dot operatorfetches its right-hand operand from its left. The dot operator applies only to objectsof class type: The left-hand operand must be an object of class type; the right-handoperand must name a member of that type.
Unlike most other operators, the right operand of the dot (“.”) opera-tor is not an object or value; it is the name of a member.
When we use a member function as the right-hand operand of the dot operator,we usually do so to call that function. We execute a member function in much thesame way as we do any function: To call a function, we follow the function nameby the call operator (the “()” operator). The call operator is a pair of parenthesesthat encloses a (possibly empty) list of arguments that we pass to the function.
The same_isbn function takes a single argument, and that argument is an-other Sales_item object. The call
item1.same_isbn(item2)
passes item2 as an argument to the function named same_isbn that is a memberof the object named item1. This function compares the ISBN part of its argument,item2, to the ISBN in item1, the object on which same_isbn is called. Thus, theeffect is to test whether the two objects refer to the same ISBN.
If the objects refer to the same ISBN, we execute the statement following theif, which prints the result of adding the two Sales_item objects together. Oth-erwise, if they refer to different ISBNs, we execute the else branch, which is ablock of statements. The block prints an appropriate error message and exits theprogram, returning -1. Recall that the return from main is treated as a status indi-cator. In this case, we return a nonzero value to indicate that the program failed toproduce the expected result.
1.6 The C++ ProgramNow we are ready to solve our original bookstore problem: We need to read afile of sales transactions and produce a report that shows for each book the totalrevenue, average sales price, and the number of copies sold.
26 Getting Started
EXE R C I S E S SE C TI ON 1.5.2
Exercise 1.24: Write a program that reads several transactions. For each new transac-tion that you read, determine if it is the same ISBN as the previous transaction, keepinga count of how many transactions there are for each ISBN. Test the program by giv-ing multiple transactions. These transactions should represent multiple ISBNs but therecords for each ISBN should be grouped together.
We’ll assume that all of the transactions for a given ISBN appear together. Ourprogram will combine the data for each ISBN in a Sales_item object namedtotal. Each transaction we read from the standard input will be stored in a sec-ond Sales_item object named trans. Each time we read a new transaction we’llcompare it to the Sales_item object in total. If the objects refer to the sameISBN, we’ll update total. Otherwise we’ll print the value in total and reset itusing the transaction we just read.
#include <iostream>#include "Sales_item.h"
int main(){
// declare variables to hold running sum and data for the next recordSales_item total, trans;
// is there data to process?if (std::cin >> total) {
// if so, read the transaction recordswhile (std::cin >> trans)
if (total.same_isbn(trans))// match: update the running totaltotal = total + trans;
else {// no match: print & assign to totalstd::cout << total << std::endl;total = trans;
}// remember to print last recordstd::cout << total << std::endl;
} else {// no input!, warn the userstd::cout << "No data?!" << std::endl;return -1; // indicate failure
}
return 0;}
This program is the most complicated one we’ve seen so far, but it uses onlyfacilities that we have already encountered. As usual, we begin by including theheaders that we use: iostream from the library and Sales_item.h, which isour own header.
Section 1.6 The C++ Program 27
Inside main we define the objects we need: total, which we’ll use to sumthe data for a given ISBN, and trans, which will hold our transactions as we readthem. We start by reading a transaction into total and testing whether the readwas successful. If the read fails, then there are no records and we fall through tothe outermost else branch, which prints a message to warn the user that therewas no input.
Assuming we have successfully read a record, we execute the code in the ifbranch. The first statement is a while that will loop through all the remainingrecords. Just as we did in the program on page 18, our while condition reads avalue from the standard input and then tests that valid data was actually read. Inthis case, we read a Sales_item object into trans. As long as the read succeeds,we execute the body of the while.
The body of the while is a single if statement. We test whether the ISBNs areequal, and if so we add the two objects and store the result in total. If the ISBNsare not equal, we print the value stored in total and reset total by assigningtrans to it. After execution of the if, we return to the condition in the while,reading the next transaction and so on until we run out of records.
Once the while completes, we still must write the data associated with the lastISBN. When the while terminates, total contains the data for the last ISBN in thefile, but we had no chance to print it. We do so in the last statement of the blockthat concludes the outermost if statement.
EXE R C I S E S SE C TI ON 1.6
Exercise 1.25: Using the Sales_item.h header from the Web site, compile and exe-cute the bookstore program presented in this section.
Exercise 1.26: In the bookstore program we used the addition operator and not thecompound assignment operator to add trans to total. Why didn’t we use the com-pound assignment operator?
28 Defined Terms
CH A P T E R SU M M A R YThis chapter introduced enough of C++ to let the reader compile and execute sim-ple C++ programs. We saw how to define a main function, which is the functionthat is executed first in any C++ program. We also saw how to define variables,how to do input and output, and how to write if, for, and while statements.The chapter closed by introducing the most fundamental facility in C++: the class.In this chapter we saw how to create and use objects of a given class. Laterchapters show how to define our own classes.
DEFINED TERMS
argument A value passed to a functionwhen it is called.
block Sequence of statements enclosed incurly braces.
buffer A region of storage used to holddata. IO facilities often store input (or out-put) in a buffer and read or write the bufferindependently of actions in the program.Output buffers usually must be explicitlyflushed to force the buffer to be written. Bydefault, reading cin flushes cout; cout isalso flushed when the program ends nor-mally.
built-in type A type, such as int, definedby the language.
cerr ostream object tied to the standarderror, which is often the same stream as thestandard output. By default, writes to cerrare not buffered. Usually used for errormessages or other output that is not part ofthe normal logic of the program.
cin istream object used to read from thestandard input.
class C++ mechanism for defining ourown data structures. The class is one of themost fundamental features in C++. Librarytypes, such as istream and ostream, areclasses.
class type A type defined by a class. Thename of the type is the class name.
clog ostream object tied to the standarderror. By default, writes to clog are
buffered. Usually used to report informa-tion about program execution to a log file.
comments Program text that is ignored bythe compiler. C++ has two kinds of com-ments: single-line and paired. Single-linecomments start with a //. Everything fromthe // to the end of the line is a comment.Paired comments begin with a /* and in-clude all text up to the next */.
condition An expression that is evaluatedas true or false. An arithmetic expressionthat evaluates to zero is false; any othervalue yields true.
cout ostream object used to write to thestandard output. Ordinarily used to writethe output of a program.
curly brace Curly braces delimit blocks.An open curly ({) starts a block; a closecurly (}) ends one.
data structure A logical grouping of dataand operations on that data.
edit-compile-debug The process of get-ting a program to execute properly.
end-of-file System-specific marker in a filethat indicates that there is no more input inthe file.
expression The smallest unit of computa-tion. An expression consists of one or moreoperands and usually an operator. Expres-sions are evaluated to produce a result. Forexample, assuming i and j are ints, theni + j is an arithmetic addition expression
Defined Terms 29
and yields the sum of the two int values.Expressions are covered in more detail inChapter 5.
for statement Control statement that pro-vides iterative execution. Often used to stepthrough a data structure or to repeat a calcu-lation a fixed number of times.
function A named unit of computation.
function body Statement block that de-fines the actions performed by a function.
function name Name by which a functionis known and can be called.
header A mechanism whereby the defini-tions of a class or other names may be madeavailable to multiple programs. A header isincluded in a program through a #includedirective.
if statement Conditional execution basedon the value of a specified condition. If thecondition is true, the if body is executed. Ifnot, control flows to the statement followingthe else if there is one or to the statementfollowing the if if there is no else.
iostream library type providing stream-oriented input and output.
istream Library type providing stream-oriented input.
library type A type, such as istream, de-fined by the standard library.
main function Function called by the op-erating system when executing a C++ pro-gram. Each program must have one andonly one function named main.
manipulator Object, such as std::endl,that when read or written “manipulates”the stream itself. Section A.3.1 (p. 825) cov-ers manipulators in more detail.
member function Operation defined by aclass. Member functions ordinarily arecalled to operate on a specific object.
method Synonym for member function.
namespace Mechanism for putting namesdefined by a library into a single place.Namespaces help avoid inadvertent nameclashes. The names defined by the C++ li-brary are in the namespace std.
ostream Library type providing stream-oriented output.
parameter list Part of the definition of afunction. Possibly empty list that speci-fies what arguments can be used to call thefunction.
preprocessor directive An instruction tothe C++ preprocessor. #include is a pre-processor directive. Preprocessor direc-tives must appear on a single line. We’lllearn more about the preprocessor in Sec-tion 2.9.2.
return type Type of the value returned bya function.
source file Term used to describe a file thatcontains a C++ program.
standard error An output stream intendedfor use for error reporting. Ordinarily, on awindowing operating system, the standardoutput and the standard error are tied to thewindow in which the program is executed.
standard input The input stream that ordi-narily is associated by the operating systemwith the window in which the program ex-ecutes.
standard library Collection of types andfunctions that every C++ compiler mustsupport. The library provides a rich setof capabilities including the types that sup-port IO. C++ programmers tend to talkabout “the library,” meaning the entirestandard library or about particular partsof the library by referring to a librarytype. For example, programmers also re-fer to the “iostream library,” meaning thepart of the standard library defined by theiostream classes.
30 Defined Terms
standard output The output stream thatordinarily is associated by the operatingsystem with the window in which the pro-gram executes.
statement The smallest independent unitin a C++ program. It is analogous to a sen-tence in a natural language. Statements inC++ generally end in semicolons.
std Name of the namespace used by thestandard library. std::cout indicates thatwe’re using the name cout defined in thestd namespace.
string literal Sequence of characters en-closed in double quotes.
uninitialized variable Variable that has noinitial value specified. There are no unini-tialized variables of class type. Variablesof class type for which no initial value isspecified are initialized as specified by theclass definition. You must give a value to anuninitialized variable before attempting touse the variable’s value. Uninitialized vari-ables can be a rich source of bugs.
variable A named object.
while statement An iterative control state-ment that executes the statement that is thewhile body as long as a specified conditionis true. The body is executed zero or moretimes, depending on the truth value of thecondition.
() operator The call operator: A pairof parentheses “()” following a functionname. The operator causes a function to beinvoked. Arguments to the function may bepassed inside the parentheses.
++ operator Increment operator. Addsone to the operand; ++i is equivalent to i= i + 1.
+= operator A compound assignment op-erator. Adds right-hand operand to the leftand stores the result back into the left-handoperand; a += b is equivalent to a = a + b.
. operator Dot operator. Takes two oper-ands: the left-hand operand is an object and
the right is the name of a member of that ob-ject. The operator fetches that member fromthe named object.
:: operator Scope operator. We’ll seemore about scope in Chapter 2. Amongother uses, the scope operator is used toaccess names in a namespace. For exam-ple, std::cout says to use the name coutfrom the namespace std.
= operator Assigns the value of the right-hand operand to the object denoted by theleft-hand operand.
<< operator Output operator. Writes theright-hand operand to the output streamindicated by the left-hand operand: cout<< "hi" writes hi to the standard output.Output operations can be chained together:cout << "hi << "bye" writes hibye.
>> operator Input operator. Reads fromthe input stream specified by the left-handoperand into the right-hand operand: cin>> i reads the next value on the stan-dard input into i. Input operations can bechained together: cin >> i >> j reads firstinto i and then into j.
== operator The equality operator. Testswhether the left-hand operand is equal tothe right-hand.
!= operator Assignment operator. Testswhether the left-hand operand is not equalto the right-hand.
<= operator The less-than-or-equal opera-tor. Tests whether the left-hand operand isless than or equal to the right-hand.
< operator The less-than operator. Testswhether the left-hand operand is less thanthe right-hand.
>= operator Greater-than-or-equal opera-tor. Tests whether the left-hand operand isgreater than or equal to the right-hand.
> operator Greater-than operator. Testswhether the left-hand operand is greaterthan the right-hand.
Index
Bold face numbers refer to the page on which the term was first defined.Numbers in italic refer to the “Defined Terms” section in which the term is defined.
... (ellipsis parameter), 244/* */ (block comment), 10, 28// (single-line comment), 10, 28_ _DATE_ _ , 221_ _FILE_ _ , 221_ _LINE_ _ , 221_ _TIME_ _ , 221_ _cplusplus, 803\0 (null character), 40\Xnnn (hexadecimal escape sequence), 40\n (newline character), 40\t (tab character), 40{ } (curly brace), 3, 28#define, 71#ifdef, 71#ifundef, 71#include, 7~classname, see destructorL’c’ (wchar_t literal), 40ctrl-d (Unix end-of-file), 20ctrl-z (Windows end-of-file), 20; (semicolon), 3
class definition, 440++ (increment), 13, 30, 146, 190
and dereference, 163iterator, 98, 108, 312overloaded operator, 527pointer, 114prefix yields lvalue, 162reverse iterator, 412
-- (decrement), 190and dereference, 163iterator, 312overloaded operator, 527prefix yields lvalue, 162reverse iterator, 412
* (dereference), 98, 108, 146, 389iterator, 98
on map yields pair, 362overloaded operator, 524pointer, 119yields lvalue, 99, 120
& (address-of), 115, 146, 511-> (arrow operator), 164
class member access, 445overloaded operator, 525
->* (pointer to member arrow), 783[ ] (subscript), 87, 108, 146
bitset, 105deque, 325map, 363string, 87vector, 94, 325and multi-dimensioned array, 142and pointer, 124array, 113overloaded operator, 522
reference return, 522valid subscript range, 88yields lvalue, 88
() (call operator), 25, 30, 226, 280overloaded operator, 530
:: (scope operator), 8, 30, 78, 108base class members, 569class member, 85, 445container defined type, 317member function definition, 262to override name lookup, 449
= (assignment), 13, 30, 159and conversion, 179and equality, 161class assignment operator, 476container, 328overloaded operator, 483, 520
and copy constructor, 484check for self-assignment, 490
843
844 Index
Message, 490multiple inheritance, 737reference return, 483, 521rule of three, 485use counting, 495, 498valuelike classes, 501
pointer, 120string, 86to signed, 37to unsigned, 37yields lvalue, 160
+= (compound assignment), 13, 30, 161string, 86iterator, 313overloaded operator, 511Sales_item, 521
+ (addition), 150string, 86iterator, 101, 313pointer, 123Sales_item, 517
- (subtraction), 150iterator, 101, 313pointer, 123
* (multiplication), 150/ (division), 150% (modulus), 151== (equality), 30, 154
string, 85algorithm, 421container, 322container adaptor, 350iterator, 98, 312string, 347
!= (inequality), 30, 154container, 322container adaptor, 350iterator, 98, 312string, 347
< (less-than), 30, 153overloaded and containers, 520used by algorithm, 420
<= (less-than-or-equal), 13, 30, 153> (greater-than), 30, 153>= (greater-than-or-equal), 30, 153>> (input operator), 8, 30
Sales_item, 516istream_iterator, 408string, 81, 108overloaded operator, 515
must be nonmember, 514
precedence and associativity, 158<< (output operator), 7, 30
bitset, 106ostream_iterator, 408string, 81, 108formatting, 514overloaded operator, 513
must be nonmember, 514precedence and associativity, 158Sales_item, 514
>> (right-shift), 155, 190<< (left-shift), 155, 190&& (logical AND), 152
operand order of evaluation, 172overloaded operator, 511
|| (logical OR), 152operand order of evaluation, 172overloaded operator, 511
& (bitwise AND), 156, 189Query, 610
! (logical NOT), 153| (bitwise OR), 156, 190
example, 290Query, 610
^ (bitwise XOR), 156, 190~ (bitwise NOT), 155, 189
Query, 610, (comma operator), 168, 189
example, 289operand order of evaluation, 172overloaded operator, 511
?: (conditional operator), 165, 189operand order of evaluation, 172
+ (unary plus), 150- (unary minus), 150\nnn (octal escape sequence), 40ddd.dddL or ddd.dddl (long double lit-
eral), 39numEnum or numenum (double literal),
39numF or numf (float literal), 39numL or numl (long literal), 39numU or numu (unsigned literal), 39class member:constant expression, see bit-
field
Aabnormal termination, stream buffers, 292abort, 692, 748absInt, 530
Index 845
abstract base class, 596, 621example, 609
abstract data type, 78, 429, 473abstraction, data, 432, 474access control, 65
in base and derived classes, 570local class, 796nested class, 787using declarations to adjust, 573
access label, 65, 73, 432, 473private, 65, 432protected, 562, 622public, 65, 432
Account, 468accumulate, 396, 823Action, 783adaptor, 348, 353
container, 348function, 533, 535, 553iterator, 399
addition (+), 150string, 86iterator, 101, 313pointer, 123Sales_item, 517
address, 35, 73address-of (&), 115, 146
overloaded operator, 511adjacent_difference, 824adjacent_find, 813algorithm, 392, 424
_copy versions, 400, 421_if versions, 421element type constraints, 394independent of container, 393iterator argument constraints, 397, 415iterator category and, 416, 418naming convention, 420–421overloaded versions, 420parameter pattern, 419–420passing comparison function, 403read-only, 396structure, 419that reorders elements, 421that writes elements, 398type independence, 394, 396using function object as argument,
531with two input ranges, 420
algorithm header, 395alias, namespace, 720, 750
allocator, 755, 755–759, 805allocate, 759
compared to operator new, 761construct, 755, 758
compared to placement new, 762deallocate, 759
compared to operator delete,761
destroy, 755, 759compared to calling destructor, 763
operations, 756alternative operator name, 46ambiguous
conversion, 541–544multiple inheritance, 734
function call, 269, 272, 280multiple base classes, 738
overloaded operator, 550AndQuery, 609
definition, 618eval function, 619
anonymous union, 795, 805app (file mode), 296append, string, 342argc, 244argument, 25, 28, 226, 227, 280
array type, 238C-style string, 242const reference type, 235conversion, 229
with class type conversion, 541copied, 230
uses copy constructor, 478default, 253iterator, 238, 242multi-dimensioned array, 241passing, 229pointer to const, 231pointer to nonconst, 231reference parameter, 233template, see template argumentto main, 243to member function, 260nonconst reference parameter, 235type checking, 229
ellipsis, 244of array type, 239of reference to array, 240with class type conversion, 541
argument deduction, template, 637argument list, 226
846 Index
argv, 244arithmetic
iterator, 100, 107, 312, 313pointer, 123, 146
arithmetic operatorand compound assignment, 162function object, 533overloaded operator, 517
arithmetic type, 34, 73conversion, 180, 188
from bool, 182signed to unsigned, 36
conversion to bool, 182array, 40, 73, 110–114
and pointer, 122argument, 238as initializer of vector, 140assignment, 112associative, 388conversion to pointer, 122, 181
and template argument, 639copy, 112default initialization, 111
uses copy constructor, 478uses default constructor, 460
definition, 110elements and destructor, 485function returning, 228initialization, 111multi-dimensioned, 141–144
and pointer, 143definition, 142initialization, 142parameter, 241subscript operator, 142
of char initialization, 112parameter, 238–244
buffer overflow, 242convention, 241–243reference type, 240
size calculation, 309and sizeof, 167subscript operator, 113
arrow operator (->), 164auto_ptr, 704class member access, 445generic handle, 670overloaded operator, 525
assert preprocessor macro, 221, 223assign
container, 328
string, 340assignment
vs. initialization, 49memberwise, 483, 503
assignment (=), 13, 30, 159, 502and conversion, 179and copy constructor, 484check for self-assignment, 490container, 328for derived class, 586Message, 490multiple inheritance, 737overloaded operator, 476, 483, 520
reference return, 483, 521pointer, 120rule of three, 485
exception for virtual destructors,588
string, 86synthesized, 483, 503to base from derived, 578to signed, 37to unsigned, 37use counting, 495, 498usually not virtual, 588valuelike classes, 501yields lvalue, 160
associative array, see map, 388associative container, 356, 388
assignment (=), 328begin, 369clear, 359constructors, 360count, 377element type constraints, 309, 323empty, 359equal_range, 379erase, 359find, 377insert, 364key type constraints, 360lower_bound, 377operations, 358overriding the default comparison,
604rbegin, 412rend, 412returning an, 381reverse_iterator, 412size, 359supports relational operators, 359
Index 847
swap, 329types defined by, 361upper_bound, 377
associativity, 149, 170, 188overloaded operator, 507
atdeque, 325vector, 325
ate (file mode), 296auto_ptr, 702, 748
constructor, 703copy and assignment, 704default constructor, 705get member, 705operations, 703pitfalls, 707reset member, 706self-assignment, 705
automatic object, 255, 280see also local variablesee also parameterand destructor, 485
Bback
queue, 352sequential container, 324
back_inserter, 399, 406, 424bad, 289bad_alloc, 175, 219bad_cast, 219, 774bad_typeid, 776badbit, 289base, 414base class, 285, 302, 558, 621
see also virtual functionabstract, 596, 621
example, 609access control, 561, 571assignment operator, usually not vir-
tual, 588can be a derived class, 566constructor, 581
calls virtual function, 589not virtual, 588
conversion from derived, 567access control, 579
definition, 560destructor
calls virtual function, 589
usually virtual, 587friendship not inherited, 575handle class, 599member operator delete, 764member hidden by derived, 593multiple, see multiple base classmust be complete type, 566no conversion to derived, 580object initialized or assigned from de-
rived, 578scope, 590static members, 576user, 563virtual, 751
see virtual base classBasket, 605
total function, 606Bear, 731
as virtual base, 741begin, 353
map, 369set, 372vector, 97container, 317
best match, 269, 280see also function matching
bidirectional iterator, 417, 424list, 417map, 417set, 417
binary (file mode), 296binary function object, 533binary operator, 148, 188binary_search, 814BinaryQuery, 609
definition, 617bind1st, 535bind2nd, 535binder, 535, 552binding, dynamic, 559, 621
requirements for, 566bit-field, 798, 805
access to, 798bitset, 101, 101–106, 107
any, 104count, 104flip, 105
compared to bitwise NOT, 155none, 104reset, 105set, 105
848 Index
size, 104test, 105to_ulong, 105compared to bitwise operator, 156constructor, 101–103header, 101output operator, 106subscript operator, 105
bitwise AND (&), 156, 189example, 610
bitwise exclusive or (^), 156, 190bitwise NOT (~), 155, 189
example, 610bitwise operator, 154–159
and compound assignment, 162compared to bitset, 156compound assignment, 157example, 290operand, 155
bitwise OR (|), 156, 190example, 290, 610
block, 3, 13, 28, 193, 223try, 216, 217, 224, 750as target of if, 196function, 227
block scope, 193body, function, 3, 29, 226, 281book finding program
using equal_range, 379using find, 377using upper_bound, 378
bookstore program, 26exception classes, 698
bool, 35and equality operator, 154conversion to arithmetic type, 182literal, 39
boolalpha manipulator, 826brace, curly, 3, 28break statement, 212, 223
and switch, 201–203buffer, 8, 28
flushing, 290buffer overflow, 114
and C-style string, 132array parameter, 242
built-in type, 3, 28, 34–37class member default initialization,
264conversion, 179initialization of, 51
Bulk_itemclass definition, 564constructor, 581constructor using default arguments,
582derived fromDisc_item, 584interface, 558member functions, 559
byte, 35, 73
CC++
calling C function from C++, 801compiling C and C++, 803using C linkage, 802
.C file, 4
.cc file, 4
.cpp file, 4
.cp file, 4C library header, 90C with classes, 430C-style cast, 186C-style string, 112, 130, 130–134, 145
and char*, 131and string literal, 140compared to string, 134, 138definition, 130dynamically allocated, 138initialization, 130parameter, 242pitfalls with generic programs, 671
c_str, 140example, 294
CachedObjadd_to_freelist, 771operator delete, 770operator new, 769allocation explained, 769definition, 767definition of static members, 771design, 766illustration, 767inheriting from, 768
call operator (()), 25, 30, 226, 280execution flow, 226overloaded operator, 530
calling C function from C++, 801candidate function, 270, 280
and function templates, 679namespaces, 728
Index 849
overloaded operator, 549capacity
string, 336vector, 331
case label, 201, 201–204, 223default, 203
cassert header, 221cast, 183, 188
checked, see dynamic_castold-style, 186
catch clause, 216, 217, 223, 693, 749catch(...), 696, 748example, 217exception specifier, 693matching, 693ordering of, 694parameter, 693
category, iterator, 425cctype, 88–89, 107
header, 88cerr, 6, 28char, 34
literal, 40char string literal, see string literalcharacter
newline (\n), 40nonprintable, 40, 75null (\0), 40printable, 88tab (\t), 40
checked cast, see dynamic_castCheckedPtr, 526children’s story program, 400
revisited, 531cin, 6, 28
by default tied to cout, 292cl, 4class, 20, 28, 63, 73, 473
static member, 474abstract base, 621
example, 609access labels, 65, 432as friend, 465base, 285, 302, see base class, 621concrete, 433conversion, 552
multiple conversions lead to am-biguities, 546
conversion constructor, 461function matching, 547with standard conversion, 540
data member, 64, 74const vs. mutable, 443const, initialization, 455constraints on type, 438definition, 435initialization, 454mutable, 443reference, initialization, 455static, 469
data member definition, 65default access label, 433default inheritance access label, 574definition, 64, 430–440
and header, 264, 437derived, 285, 302, see derived class,
621destructor definition, 486direct base, see immediate base class,
621explicit constructor, 462forward declaration, 438generic handle, 667, 683handle, see handle class, 599, 622immediate base, 566, 622indirect base, 566, 622local, see local class, 806member, 64, 73, 430member access, 445member function, 25, 29, see mem-
ber functionmember:constant expression, see bit-
fieldmultiple inheritance, see multiple base
classnested, see nested class, 806nonvirtual function, calls resolved at
compile time, 569operator delete, see member op-
eratoroperator new, see member opera-
tor newpointer member
copy control, 492–501copy control strategies, 499default copy behavior, 493
pointer to member, 780definition, 781
pointer to member function, defini-tion, 782
preventing copies, 481private member, 431
850 Index
inheritance, 561private member, 75protected member, 562public member, 75, 431
inheritance, 561static member, 467
as default argument, 471data member as constant expres-
sion, 471example, 468inheritance, 576
template member, see member tem-plate
type member, 435undefined member, 482user, 433, 563virtual base, 751virtual function, calls resolved at run
time, 569class, keyword, 64
compared to typename, 631in template parameter, 630in variable definition, 440
class keyword, 473class declaration, 438, 473
of derived class, 566class derivation list, 563, 621
access control, 570default access label, 574multiple base classes, 731virtual base, 742
class scope, 65, 444, 473friend declaration, 466inheritance, 590–595member definition, 445name lookup, 447static members, 470virtual functions, 594
class template, 90, 107, 627, 683see also template parametersee also template argumentsee also instantiationcompiler error detection, 634declaration, 629definition, 627error detection, 635explicit template argument, 636export, 645friend
declaration dependencies, 658explicit template instantiation, 657
nontemplate class or function, 656template class or function, 656
member function, 653defined outside class body, 651instantiation, 653
member specialization, 677member template, see member tem-
platenontype template parameter, 655static member, 665
accessed through an instantiation,666
definition, 666type includes template argument(s),
628, 637type-dependent code, 634uses of template parameter, 649
class template specializationdefinition, 675member, declaration, 677member defined outside class body,
676namespaces, 730
class type, 20, 28, 65class member default initialization,
264conversion, 183initialization of, 52object definition, 439parameter and overloaded operator,
507variable vs. function declaration, 460
cleanup, object, see destructorclear, 289, 290
associative container, 359example, 290, 295sequential container, 327
clog, 6, 28close, 294comma operator (,), 168, 189
example, 289operand order of evaluation, 172overloaded operator, 511
comment, 10, 28block (/* */), 10, 28single-line (//), 10, 28
compareplain function, 624string, 347template version, 625
instantiatied with pointer, 671
Index 851
specialization, 672compilation
and header, 67conditional, 220inclusion model for templates, 644needed when class changes, 434needed when inline function changes,
258separate, 67, 76
of templates, 643separate model for templates, 644
compilerextension, 112flag for inclusion compilation model,
645GNU, 4Microsoft, 4template errors diagnosed at link time,
635compiler extension, 145compiling C and C++, 803composition vs. inheritance, 573compound assignment (e.g.,+=), 13, 30, 161
string, 86bitwise operator, 157iterator, 313overloaded operator, 511, 518Sales_item, 521
compound expression, 168, 188compound statement, 193, 223compound type, 58, 73, 145compute, 542
overloaded version, 545concatenation
Screen operations, 441string, 86string literal, 41
concrete class, 433initialization, 464
condition, 13, 28and conversion, 179assignment in, 161in do while statement, 211in for statement, 15, 207in if statement, 18, 195in logical operator, 152in while statement, 205stream type as, 19, 183, 288string input operation as, 82
condition state, 287, 302conditional compilation, 220
conditional operator (?:), 165, 189operand order of evaluation, 172
console window, 6const, 57
and dynamically allocated array, 136conversion to, 182, 231
and template argument, 639iterator vs. const_iterator, 100object scope, 57, 69overloading and, 267, 275parameter, 231pointer, 128reference, 59
initialization, 60const object, constructor, 453const data member
static data member, 470compared to mutable, 443initialization, 455
const member function, 261, 262, 280,431, 473
overloaded, 442reference return, 442static, 469
const pointer, see also pointer to constconversion from nonconst, 182
const referenceargument, 235conversion from nonconst, 182parameter, 235
overloading, 275return type, 249
const void*, 127, 145const_cast, 183, 184const_iterator, 99, 415
compared to const iterator, 100container, 316
const_reference, 317const_reverse_iterator, 412
container, 316constant expression, 62, 74
and header file, 69array index, 110bit-field, 798enumerator, 62nontype template parameter, 633static data member, 471
construction, order of, 456, 749derived objects, 581, 582multiple base classes, 732virtual base classes, 746
852 Index
constructor, 49, 74, 262, 281, 431const objects, 453conversion, 461, 474
function matching, 547with standard conversion, 540
copy, 476–482, 502base from derived, 578multiple inheritance, 737
default, 52, 74, 262, 281, 458–461, 474default argument in, 458derived class, 581
initializes immediate base class, 583initializes virtual base, 744
execution flow, 454explicit, 462, 474
copy-initialization, 477for associative container, 360for sequential container, 307–309function try block, 696in constructor initializer list, 457inheritance, 581initializer, 452may not be virtual, 588object creation, 452order of construction, 456
derived objects, 581, 582multiple base classes, 732virtual base classes, 746
overloaded, 452pair, 357resource allocation, 700synthesized copy, 479, 503synthesized default, 264, 281, 459, 474virtual inheritance, 744
constructor initializer list, 263, 281, 431,453–458, 474
compared to assignment, 454derived classes, 582function try block, 696initializers, 457multiple base classes, 733sometimes required, 455virtual base class, 745
container, 90, 107, 306, 353see also sequential containersee also associative containerand generic algorithms, 393as element type, 311assignment (=), 328associative, 356, 388begin, 317
clear, 327const_iterator, 316const_reference, 317const_reverse_iterator, 316element type constraints, 309, 323elements and destructor, 485elements are copies, 318empty, 323end, 317erase, 402has bidirectional iterator, 417inheritance, 597insert, 319iterator, 316rbegin, 317, 412reference, 317rend, 317, 412returning a, 381reverse_iterator, 316, 412sequential, 306, 354size, 323size_type, 316supports relational operators, 321swap, 329types defined by, 316
continue statement, 214, 223example, 290
control, flow of, 192, 224conversion, 178, 188
ambiguous, 541–544and assignment, 159argument, 229
with class type conversion, 541arithmetic type, 180, 188array to pointer, 122, 238
and template argument, 639class type, 183, 535, 552
design considerations, 544example, 537multiple conversions lead to am-
biguities, 546operator, 537, 537–540, 552operator and function matching,
545used implicitly, 538with standard conversion, 539
constructor, 461function matching, 547with standard conversion, 540
derived to base, 567, 580access control, 579
Index 853
enumeration type to integer, 182from istream, 183function matching of template and
nontemplate functions, 681function to pointer, 277
and template argument, 639implicit, 189inheritance, 577integral promotion, 180multi-dimensioned array to pointer,
143multiple inheritance, 734nontemplate type argument, 640of return value, 246rank for function matching, 272rank of class type conversions, 545signed type, 180signed to unsigned, 36template argument, 638to const pointer, 127to const, 182
and template argument, 639parameter matching, 231
virtual base, 743conversion constructor, 474copy, 815copy constructor, 476, 476–482, 502
and assignment operator, 484argument passing, 478base from derived, 578for derived class, 586initialization, 478Message, 489parameter, 480pointer members, 480rule of three, 485
exception for virtual destructors,588
synthesized, 479, 503use counting, 495, 497valuelike classes, 500
copy control, 476, 502handle class, 601inheritance, 584–590message handling example, 489multiple inheritance, 737of pointer members, 499
copy-initialization, 48using constructor, 477
copy_backward, 816count, use, 495, 503
count, 812book finding program, 377map, 367multimap, 377multiset, 377set, 372
count_if, 404, 812with function object argument, 532
cout, 6, 28by default tied to cin, 292
cstddef header, 104, 123cstdlib header, 247cstring header, 132curly brace, 3, 28
Ddangling else, 198, 223dangling pointer, 176, 188
returning pointer to local variable,249
synthesized copy control, 494data abstraction, 432, 474
advantages, 434data hiding, 434data structure, 20, 28data type, abstract, 473dec manipulator, 827decimal literal, 38declaration, 52, 74
class, 438, 473class template member specialization,
677dependencies and template friends,
658derived class, 566export, 645forward, 438, 474function, 251
exception specification, 708function template specialization, 672,
673member template, 661template, 629using, 78, 108, 720, 750
access control, 573class member access, 574overloaded inherited functions, 593
declaration statement, 193, 224decrement (--), 190
iterator, 312
854 Index
overloaded operator, 526prefix yields lvalue, 162reverse iterator, 412
deduction, template argument, 637default argument, 253
and header file, 254function matching, 270in constructor, 458initializer, 254overloaded function, 267virtual functions, 570
default case label, 203, 224default constructor, 52, 74, 262, 281, 458–
461, 474Sales_item, 263string, 52, 81default argument, 458synthesized, 264, 281, 459, 474used implicitly, 459variable definition, 460
definition, 52, 74array, 110base class, 560C-style string, 130class, 64, 430–440class data member, 65, 435class static member, 469class template, 627static member, 666
class template specialization, 675member defined outside class body,
676class type object, 439derived class, 563destructor, 486dynamically allocated array, 135dynamically allocated object, 174function, 3inside an if condition, 196inside a switch expression, 203inside a while condition, 205map, 360, 373multi-dimensioned array, 142namespace, 712
can be discontiguous, 714member, 716
of variable after case label, 204overloaded operator, 482pair, 356pointer, 115pointer to function, 276
static data member, 470variable, 48
delete, 145, 176, 188, 806compared to operatordelete, 760const object, 178execution flow, 760member operator, 806member operator
and inheritance, 764interface, 764
memory leak, 177, 485null pointer, 176runs destructor, 485
delete [], 135and dynamically allocated array, 137
deque, 353as element type, 311assign, 328assignment (=), 328at, 325back, 324begin, 317clear, 327const_iterator, 316const_reference, 317const_reverse_iterator, 316constructor from element count, uses
copy constructor, 478constructors, 307–309difference_type, 316element type constraints, 309, 323empty, 323end, 317erase, 326
invalidates iterator, 326front, 324insert, 319
invalidates iterator, 320iterator, 316iterator supports arithmetic, 312performance characteristics, 334pop_back, 326pop_front, 326push_back, 318
invalidates iterator, 321push_front, 318
invalidates iterator, 321random-access iterator, 417rbegin, 317, 412reference, 317relational operators, 321
Index 855
rend, 317, 412resize, 323reverse_iterator, 316, 412size, 323size_type, 316subscript ([ ]), 325supports relational operators, 313swap, 329types defined by, 316value_type, 317
dereference (*), 98, 108, 146, 389and increment, 163auto_ptr, 704iterator, 98on map iterator yields pair, 362overloaded operator, 524pointer, 119yields lvalue, 99, 120
derivation list, class, 563, 621access control, 570default access label, 574
derived class, 285, 302, 558, 621see also virtual functionaccess control, 561, 572as base class, 566assgined or copied to base object, 578assignment (=), 586constructor, 581
calls virtual function, 589for remote virtual base, 744initializes immediate base class, 583
constructor initializer list, 582conversion to base, 567
access control, 579copy constructor, 586default derivation label, 574definition, 563destructor, 587
calls virtual function, 589friendship not inherited, 576handle class, 599member operator delete, 764member hides member in base, 593multiple base classes, 731no conversion from base, 580scope, 590scope (::) to access base class mem-
ber, 569static members, 576using declaration
inherited functions, 593
member access, 574with remote virtual base, 742
derived objectcontains base part, 565multiple base classes, contains base
part for each, 732design
CachedObj, 766class member access control, 563class type conversions, 544consistent definitions of equality and
relational operators, 520is-a relationship, 573Message class, 486namespace, 714of handle classes, 599of header files, 67export, 646inclusion compilation model, 644separate compilation model, 645
optimizing new and delete, 764using freelist, 766
overloaded operator, 510–513overview of use counting, 495Query classes, 609–611Queue, 647resource allocation is initialization,
700–701Sales_item handle class, 599TextQuery class, 380vectormemory allocation strategy,
756writing generic code, 634
pointer template argument, 671destruction, order of, 749
derived objects, 587multiple base classes, 733virtual base classes, 747
destructor, 476, 484, 502called during exception handling, 691container elements, 485definition, 486derived class, 587explicit call to, 762implicitly called, 484library classes, 709Message, 491multiple inheritance, 737order of destruction, 485
derived objects, 587multiple base classes, 733
856 Index
virtual base classes, 747resource deallocation, 700rule of three, 485
exception for virtual destructors,588
should not throw exception, 692synthesized, 485, 486use counting, 495, 497valuelike classes, 500virtual, multiple inheritance, 736virtual in base class, 587
development environment, integrated, 3difference_type, 101, 107, 316dimension, 110, 145direct base class, see immediate base class,
621direct-initialization, 48
using constructor, 477directive, using, 721, 751
pitfalls, 724Disc_item, 583
class definition, 583discriminant, 794, 806divides<T>, 534division (/), 150do while statement, 210
condition in, 211domain_error, 219dot operator (.), 25, 30
class member access, 445double, 37
literal (numEnum or numenum), 39long double, 37notation outptu format control, 830output format control, 828
duplicate word program, 400–404revisited, 531
dynamic binding, 559, 621in C++, 569requirements for, 566
dynamic type, 568, 622dynamic_cast, 183, 773, 806
example, 773throws bad_cast, 774to pointer, 773to reference, 774
dynamically allocated, 145const object, 177array, 134, 134–139delete, 137definition, 135
initialization, 136of const, 136
C-style string, 138memory and object construction, 754object, 174auto_ptr, 702constructor, 453destructor, 485exception, 700
Eedit-compile-debug, 16, 28
errors at link time, 635else, see if statement
dangling, 198, 223empty
string, 83, 107vector, 93, 107associative container, 359container, 323priority_queue, 352queue, 352stack, 351
encapsulation, 432, 474advantages, 434
end, 353map, 369set, 372vector, 97container, 317
end-of-file, 19, 28, 835entering from keyboard, 20
Endangered, 731endl, 8
manipulator flushes the buffer, 291ends, manipulator flushes the buffer, 291enum keyword, 62enumeration, 62, 74
conversion to integer, 182function matching, 274
enumerator, 62, 74conversion to integer, 182
environment, integrated development, 3eof, 289eofbit, 289equal, 814equal member function, 778equal_range, 814
associative container, 379book finding program, 379
Index 857
equal_to<T>, 534equality (==), 30, 154
string, 85algorithm, 421and assignment, 161container, 322container adaptor, 350iterator, 98, 312overloaded operator, 512, 518
consistent with equality, 520string, 347
eraseassociative container, 359container, 402invalidates iterator, 326map, 368multimap, 376multiset, 376sequential container, 326set, 372string, 340
error, standard, 6escape sequence, 40, 74
hexadecimal (\Xnnn), 40octal (\nnn), 40
evaluationorder of, 149, 189short-circuit, 152
exception, raise, see throwexception
class, 216, 224class hierarchy, 698constructor, 220extending the hierarchy, 697header, 219what member, 218, 697
exception handling, 215–220, 749see also throwsee also catch clauseand terminate, 219compared to assert, 221exception in destrutor, 692finding a catch clause, 693function try block, 696, 749handler, see catch clauselibrary class destructors, 709local objects destroyed, 691specifier, 217, 224, 693, 749
nonreference, 693reference, 694types related by inheritance, 694
stack unwinding, 691uncaught exception, 692unhandled exception, 219
exception object, 690, 749array or function, 689initializes catch parameter, 693must be copyable, 689pointer to local object, 690rethrow, 695
exception safety, 700, 749exception specification, 706, 749
throw(), 708function pointers, 711unexpected, 708violation, 708virtual functions, 710
executable file, 4EXIT_FAILURE, 247EXIT_SUCCESS, 247explicit constructor, 462, 474
copy-initialization, 477export, 645
and header design, 646keyword, 645, 683
exporting C++ to C, 802expression, 7, 28, 148, 189
and operand conversion, 179compound, 168, 188constant, 62, 74throw, 689, 750
expression statement, 192, 224extended_compute, 542extension, compiler, 145extern, 53extern ’C’, see linkage directiveextern const, 57
Ffactorial program, 250fail, 289failbit, 289file
executable, 4object, 68source, 4, 29
file mode, 296, 302combinations, 298example, 299
file static, 719, 749fill, 816
858 Index
fill_n, 815find, 392, 812
book finding program, 377map, 368multimap, 377multiset, 377set, 372string, 344
find last word program, 414find_first_of, 812find_first_not_of, string, 346find_end, 812find_first_of, 396, 812
string, 345find_if, 421, 812find_last_not_of, string, 346find_last_of, string, 346find_val program, 234fixed manipulator, 830float, 37
literal (numF or numf), 39floating point
notation output format control, 830output format control, 828
floating point literal, see double literalflow of control, 192, 224flush, manipulator flushes the buffer, 291Folder, see Messagefor statement, 29, 207
condition in, 207execution flow, 208expression, 207for header, 207initialization statement, 207scope, 15
for statementfor statement, 14for_each, 813format state, 825forward declaration of class type, 438forward iterator, 417, 424fp_compute, 542free store, 135, 145freelist, 766, 806friend, 465, 474
class, 465class template
explicit template instantiation, 657nontemplate class or function, 656template class or function, 656
function template, example, 659inheritance, 575
member function, 466overloaded function, 467overloaded operator, 509scope considerations, 466
namespaces, 727template example, 658
friend keyword, 465front
queue, 352sequential container, 324
front_inserter, 406, 424compared to inserter, 406
fstream, 285, 293–299, 302see also istreamsee also ostreamclose, 294constructor, 293file marker, 838file mode, 296
combinations, 298example, 299
file random access, 838header, 285, 293off_type, 839open, 293pos_type, 839random IO sample program, 840seek and tell members, 838–842
function, 2, 29, 225, 281equal member, 778inline, 257, 281candidate, 270, 280conversion to pointer, 277
and template argument, 639function returning, 228inline and header, 257member, 25, 29, see member function,
474nonvirtual, calls resolved at compile
time, 569overloaded, 265, 281
compared to redeclaration, 266friend declaration, 467scope, 268virtual, 593
pure virtual, 596, 622example, 609
recursive, 249, 281viable, 270, 282virtual, 559, 566–570, 622
assignment operator, 588
Index 859
calls resolved at run time, 568compared to run-time type iden-
tification, 777default argument, 570derived classes, 564destructor, 587destructor and multiple inheritance,
736exception specifications, 710in constructors, 589in destructor, 589introduction, 561multiple inheritance, 735no virtual constructor, 588overloaded, 593overloaded operator, 615overriding run-time binding, 570return type, 564run-time type identification, 772scope, 594to copy unknown type, 602type-sensitive equality, 778
function adaptor, 533, 535, 553bind1st, 535bind2nd, 535binder, 535negator, 535not1, 535not2, 535
function body, 3, 29, 226, 281function call
ambiguous, 269, 272execution flow, 226overhead, 257through pointer to function, 278through pointer to member, 784to overloaded operator, 509to overloaded postfix operator, 529using default argument, 253
function declaration, 251and header file, 252exception specification, 708
function definition, 3function matching, 269, 281
and overloaded function templates,679–682
examples, 680argument conversion, 269conversion operator, 545conversion rank, 272
class type conversions, 545
enumeration parameter, 274integral promotion, 273multiple parameters, 272namespaces, 727of member functions, 436overloaded operator, 547–551
function name, 3, 29function object, 531, 553
algorithms, 531example, 534
binary, 533library defined, 533unary, 533
function pointer, 276–279and template argument deduction,
640definition, 276exception specifications, 711function returning, 228initialization, 277overloaded functions, 279parameter, 278return type, 278typedef, 276
function prototype, 251, 281function return type, 226, 227, 281
const reference, 249no implicit return type, 228nonreference, 247
uses copy constructor, 478reference, 248reference yields lvalue, 249void, 245
function scope, 227function table, 785
pointer to member, 785function template, 625, 683
see also template parametersee also template argumentsee also instantiationas friend, 659compiler error detection, 634declaration, 629error detection, 635explicit template argument, 642
and function pointer, 643specifying, 642
export, 645inline, 626instantiation, 637template argument deduction, 637
860 Index
type-dependent code, 634function template specialization
compared to overloaded function, 673declaration, 672, 673example, 672namespaces, 730scope, 674
function try block, 696, 749
Gg++, 4gcd program, 226generate, 816generate_n, 815generic algorithm, see algorithmgeneric handle class, 667, 683generic memory management, see CachedObjgeneric programming, 95, 624
and pointer template argument, 671type-independent code, 634
getline, 82, 107example, 300, 386
global namespace, 716, 750global scope, 54, 74global variable, lifetime, 254GNU compiler, 4good, 289goto statement, 214, 224greater-than (>), 30, 153greater-than-or-equal (>=), 30, 153greater<T>, 534greater_equal<T>, 534GT6 program, 403GT_cls, 532guard header, 71, 74
H.h file, 21Handle, 667
int instantiation, 668operations, 668Sales_item instantiation, 669
handle class, 599, 622copy control, 601copying unknown type, 602design, 599generic, 667, 683that hides inheritance hierarchy, 610using a, 603
handler, see catch clausehas-a relationship, 573HasPtr
as a smart pointer, 495using synthesized copy control, 493with value semantics, 499
header, 7, 29, 67, 74bitset, 101cctype, 88, 107cstddef, 104iomanip, 829string, 80vector, 90algorithm, 395and constant expression, 69and library names, 810C library, 90cassert, 221class definition, 264, 437cstddef, 123cstdlib, 247cstring, 132default argument, 254deque, 307design, 67export, 646inclusion compilation model, 644namespace members, 714separate compilation model, 645
exception, 219fstream, 285, 293function declaration, 252inline function, 257inlinemember function definition,
437iostream, 285iterator, 399list, 307map, 360, 375new, 219numeric, 395programmer-defined, 67–72queue, 349Sales_item, 21, 67, 264set, 373, 375sstream, 285, 300stack, 349stdexcept, 217, 219type_info, 219using declaration, 80utility, 356
Index 861
vector, 307header file, naming convention, 264header guard, 71, 74heap, 135, 145hex manipulator, 827hexadecimal, literal (0Xnum or 0xnum),
38hexadecimal escape sequence (\Xnnn), 40hides, names in base hidden by names in
derived, 592hierarchy, inheritance, 558, 566, 622high-order bits, 102, 107
IIDE, 3identification, run-time type, 772–780, 807identifier, 46, 74
naming convention, 47reserved, 47
if statement, else branch, 224if statement, 17, 29, 195, 224
compared to switch, 199dangling else, 198else branch, 18, 197
ifstream, 285, 293–299see also istreamclose, 294constructor, 293file marker, 838file mode, 296
combinations, 298example, 299
file random access, 838off_type, 839open, 293pos_type, 839random IO sample program, 840seek and tell members, 838–842
immediate base class, 566, 622implementation, 63, 74, 432implementation inheritance, 573implicit this pointer, overloaded opera-
tor, 508implicit conversion, see conversion, 189implicit return, 245
from main allowed, 247implicit this pointer, 260, 281, 431, 440
in and overloaded operator, 483static member functions, 469
in (file mode), 296
include, see #includeincludes, 822inclusion compilation model, 644, 683incomplete type, 438, 474
restriction on use, 438, 566, 693increment (++), 13, 30, 146, 190
reverse iterator, 412and dereference, 163iterator, 98, 108, 312overloaded operator, 526pointer, 114prefix yields lvalue, 162
indentation, 14, 197index, 87, 107indirect base class, 566, 622inequality (!=), 30, 154
iterator, 98container, 322container adaptor, 350iterator, 312overloaded operator, 512, 519string, 347
inheritance, 284, 302containers, 597conversions, 577default access label, 574friends, 575handle class, 599implementation, 573interface, 573iostream diagram, 285multiple, see multiple base class, 731private, 622static members, 576virtual, 741, 751
inheritance hierarchy, 558, 566, 622inheritance vs. composition, 573initialization, 9
vs. assignment, 49array, 111array of char, 112built-in type, 51C-style string, 130class data member, 454class member of built-in type, 264class member of class type, 264class type, 52, 452const static data member, 470dynamically allocated array, 136dynamically allocated object, 174map, 373
862 Index
memberwise, 479, 503multi-dimensioned array, 142objects of concrete class type, 464pair, 356parameter, 229pointer, 117–119pointer to function, 277return value, 247value, 92, 108variable, 48, 50, 76
initialization vs. assignment, 456initialized, 48, 75initializer list, constructor, 263, 281, 431,
453–458, 474inline function, 257, 281
and header, 257function template, 626member function, 437
and header, 437inner_product, 823inplace_merge, 816input, standard, 6input (>>), 8, 30
Sales_item, 516istream_iterator, 408string, 81, 108overloaded operator, 515
error handling, 516–517must be nonmember, 514
precedence and associativity, 158input iterator, 416, 424insert
inserter, 406invalidates iterator, 320map, 364multimap, 376multiset, 376return type fromset::insert, 373sequential container, 319set, 373string, 340
insert iterator, 399, 405, 425inserter, 406inserter, 425
compared to front_inserter, 406instantiation, 625, 684
class template, 628, 636, 654member function, 653nontype parameter, 655type, 637
error detection, 635
function template, 637from function pointer, 640nontemplate argument conversion,
640nontype template parameter, 633template argument conversion, 638
member template, 663nested class template, 788, 791on use, 636static class member, 665
int, 34literal, 38
Integral, 539integral promotion, 180, 189
function matching, 273integral type, 34, 75integrated development environment, 3interface, 63, 75, 432interface inheritance, 573internal manipulator, 832interval, left-inclusive, 314, 354invalid_argument, 219invalidated iterator, 315, 353IO stream, see streamiomanip header, 829iostate, 289iostream, 6, 29, 285
see also istreamsee also ostreamheader, 285inheritance hierarchy, 740seek and tell members, 838
is-a relationship, 573isalnum, 88isalpha, 88ISBN, 2isbn_mismatch, 699
destructor explained, 709iscntrl, 88isdigit, 88isgraph, 88islower, 88isprint, 88ispunct, 88isShorter program, 235, 403isspace, 88istream, 6, 29, 285
see also manipulatorcondition state, 287flushing input buffer, 290format state, 825
Index 863
gcount, 837get, 834
multi-byte version, 836returns int, 835, 836
getline, 82, 836getline, example, 300ignore, 837inheritance hierarchy, 740input (>>), 8
precedence and associativity, 158no containers of, 310no copy or assign, 287peek, 834put, 834putback, 835read, 837seek and tell members, 838unformatted operation, 834
multi-byte, 837single-byte, 834
unget, 835write, 837
istream_iterator, 407, 425and class type, 410constructors, 408input iterator, 417input operator (>>), 408limitations, 411operations, 409used with algorithms, 411
istringstream, 285, 299–301see also istreamword per line processing, 300, 370str, 301word per line processing, 386
isupper, 88isxdigit, 88Item_base
class definition, 560constructor, 580interface, 558member functions, 559
iter_swap, 816iterator, 95, 95–101, 107, 311–316, 354
argument, 238arrow (->), 164bidirectional, 417, 424compared to reverse iterator, 413, 414destination, 399, 419equality, 98, 312forward, 417, 424
generic algorithms, 394inequality, 98, 312input, 416, 424insert, 399, 405, 425invalidated, 315, 353invalidated byassign, 328erase, 326insert, 321push_back, 321push_front, 321resize, 324
off-the-end, 97, 394, 425operations, 311output, 416, 425parameter, 238, 242random-access, 417, 425relational operators, 313reverse, 405, 412–415, 425stream, 425
iterator, 362, 374container, 316
iterator header, 399iterator arithmetic, 100, 107, 312, 313
relational operators, 313iterator category, 416–418, 425
algorithm and, 416, 418bidirectional iterator, 417forward iterator, 417hierarchy, 417input iterator, 416output iterator, 416random-access iterator, 417
iterator range, 314, 314–316, 354algorithms constraints on, 397, 415erase, 327generic algorithms, 394insert, 320
Kkey_type, 388
associative containers, 362keyword
enum, 62friend, 465namespace, 712protected, 562template, 625try, 217union, 793
864 Index
virtual, 559export, 645
keyword table, 46Koenig lookup, 726
Llabel
case, 201, 201–204, 223access, 65, 73, 432, 473statement, 214
labeled statement, 214, 224left manipulator, 832left-inclusive interval, 314, 354left-shift (<<), 155, 190length_error, 219less-than (<), 30, 153
overloaded and containers, 520used by algorithm, 420
less-than-or-equal (<=), 13, 30, 153less<T>, 534less_equal<T>, 534lexicographical_compare, 823library, standard, 5, 29library names to header table, 810library type, 29lifetime, object, 254, 281link time errors from template, 635linkage directive, 801, 806
C++ to C, 802compound, 802overloaded function, 803parameter or return type, 804pointer to function, 803single, 801
linking, 68, 75list, 354
as element type, 311assign, 328assignment (=), 328back, 324begin, 317bidirectional iterator, 417clear, 327const_iterator, 316const_reference, 317const_reverse_iterator, 316constructor from element count, uses
copy constructor, 478constructors, 307–309element type constraints, 309, 323
empty, 323end, 317erase, 326front, 324insert, 319iterator, 316merge, 423performance characteristics, 334pop_back, 326pop_front, 326push_back, 318push_front, 318rbegin, 317, 412reference, 317relational operators, 321remove, 423remove_if, 423rend, 317, 412resize, 323reverse, 423reverse_iterator, 316, 412size, 323size_type, 316specific algorithms, 421splice, 423swap, 329types defined by, 316unique, 423value_type, 317
literal, 37, 37–42, 75bool, 39char, 40decimal, 38double (numEnum or numenum), 39float (numF or numf), 39hexadecimal (0Xnum or 0xnum), 38int, 38long (numL or numl), 38long double (ddd.dddL or ddd.dddl),
39multi-line, 42octal (0num), 38string, 9, 30, 40unsigned (numU or numu), 39wchar_t, 40
local class, 796, 806access control, 796name lookup, 797nested class in, 797restrictions on, 796
local scope, 54, 75
Index 865
local static object, 255, 281local variable, 227, 281
destructor, 485lifetime, 254reference return type, 248
logic_error, 219logical AND (&&), 152
operand order of evaluation, 172overloaded operator, 511
logical NOT (!), 153logical operator, 152
function object, 533logical OR (||), 152
operand order of evaluation, 172overloaded operator, 511
logical_and<T>, 534logical_not<T>, 534logical_or<T>, 534long, 34
literal (numL or numl), 38long double, 37long double, literal (ddd.dddL or ddd.dddl),
39lookup, name, 447, 474
and templates, 647before type checking, 269, 593
multiple inheritance, 738class member declaration, 447class member definition, 448, 450class member definition, examples,
449collisions under inheritance, 591depends on static type, 590
multiple inheritance, 735inheritance, 590, 595local class, 797multiple inheritance, 737
ambiguous names, 738namespace names, 724
argument-dependent lookup, 726nested class, 791overloaded virtual functions, 593virtual inheritance, 743
low-order bits, 102, 107lower_bound, 814
associative container, 377book finding program, 378
lvalue, 45, 75assignment, 160dereference, 99function reference return type, 249
prefix decrement, 162prefix increment, 162subscript, 88
Mmachine-dependent
bitfield layout, 798char representation, 36division and modulus result, 151end-of-file character, 20iostate type, 288linkage directive language, 802nonzero return from main, 247pre-compiled headers, 67random file access, 837reinterpret_cast, 185representation of enum type, 274return from exception what oper-
ation, 220signed and out-of-range value, 37signed types and bitwise operators,
155size of arithmetic types, 34template compilation optimization,
645terminate function, 219type_info members, 779vectormemory allocation size, 331volatile implementation, 799
magic number, 56, 75main, 2, 29
arguments to, 243not recursive, 251return type, 3return value, 2–5, 247returns 0 by default, 247
make_pair, 358make_plural program, 248manip, 542manipulator, 8, 29, 825
boolalpha, 826dec, 827fixed, 830hex, 827internal, 832left, 832noboolalpha, 827noshowbase, 828noshowpoint, 832noskipws, 833
866 Index
nouppercase, 828oct, 827right, 832scientific, 830setfill, 832setprecision, 829setw, 832showbase, 827showpoint, 831skipws, 833uppercase, 828boolalpha, 826change format state, 825dec, 827endl flushes the buffer, 291ends flushes the buffer, 291fixed, 830flush flushes the buffer, 291hex, 827internal, 832left, 832noboolalpha, 827noshowbase, 828noshowpoint, 832noskipws, 833nouppercase, 828oct, 827right, 832scientific, 830setfill, 832setprecision, 829setw, 832showbase, 827showpoint, 831skipws, 833unitbuf flushes the buffer, 291uppercase, 828
map, 356, 388as element type, 311assignment (=), 328begin, 369bidirectional iterator, 417clear, 359constructors, 360count, 367definition, 360dereference yields pair, 362element type constraints, 309empty, 359end, 369equal_range, 379
erase, 359, 368find, 368header, 360insert, 364iterator, 362key type constraints, 360key_type, 362lower_bound, 377mapped_type, 362, 388operations, 358overriding the default comparison,
604rbegin, 412rend, 412return type from insert, 365reverse_iterator, 412size, 359subscript operator, 363supports relational operators, 359swap, 329upper_bound, 377value_type, 361
mapped_type, map, multimap, 362match, best, 269, 280max, 822max_element, 822member, see also class member
mutable data, 474pointer to, 780, 807
member function, 25, 29, 431, 474const, 280equal, 778as friend, 466base member hidden by derived, 593class template, 653
defined outside class body, 651instantiation, 653
const, 261, 262defined outside class body, 261, 431definition, 258–262
in class scope, 445name lookup, 448name lookup, examples, 449
function template, see member tem-plate
implicitly inline, 259inline, 437
and header, 437overloaded, 436overloaded on const, 442overloaded operator, 483, 508
Index 867
pointer to, definition, 782returning *this, 442static, 467this pointer, 469
undefined, 482member operator delete, 764, 806
and inheritance, 764example, 769CachedObj, 770interface, 764
member operator delete [], 765member operator new, 764, 806
example, 769CachedObj, 769interface, 764
member operator new [], 765member template, 660, 684
declaration, 661defined outside class body, 662examples, 660instantiation, 663template parameters, 663
memberwise assignment, 483, 503memberwise initialization, 479, 503memory exhaustion, 175memory leak, 177, 485
after exception, 700memory management, generic, see CachedObjmerge, 816
list, 423Message, 486–491
assignment operator, 490class definition, 488copy constructor, 489design, 486destructor, 491put_Msg_in_Folder, 489remove_Msg_from_Folder, 491
method, see member function, 29Microsoft compiler, 4min, 822min_element, 822minus<T>, 534mismatch, 814mode, file, 296, 302modulus (%), 151modulus<T>, 534multi-dimensioned array, 141–144
and pointer, 143conversion to pointer, 143definition, 142
initialization, 142parameter, 241subscript operator, 142
multi-line literal, 42multimap, 375, 388
assignment (=), 328begin, 369clear, 359constructors, 360count, 377dereference yields pair, 362element type constraints, 309empty, 359equal_range, 379erase, 359, 376find, 377has no subscript operator, 376insert, 376iterator, 362, 376key type constraints, 360key_type, 362lower_bound, 377mapped_type, 362operations, 358, 376overriding the default comparison,
604rbegin, 412rend, 412return type from insert, 365reverse_iterator, 412size, 359supports relational operators, 359swap, 329upper_bound, 377value_type, 361
multiple base class, 750see also virtual base classambiguities, 738ambiguous conversion, 734avoiding potential name ambiguities,
738conversions, 734definition, 731destructor usually virtual, 736name lookup, 737object composition, 732order of construction, 732scope, 737virtual functions, 735
multiple inheritance, see multiple base class,731
868 Index
multiplication (*), 150multiplies<T>, 534multiset, 375, 388
assignment (=), 328begin, 372clear, 359constructors, 372count, 377element type constraints, 309end, 372equal_range, 379erase, 359, 376find, 377insert, 376iterator, 376key type constraints, 360lower_bound, 377Sales_item, 605operations, 358, 376overriding the default comparison,
604rbegin, 412rend, 412return type from insert, 373reverse_iterator, 412supports relational operators, 359swap, 329upper_bound, 377
example, 607value_type, 372
mutable data member, 443, 474
N\n (newline character), 40name lookup, 447, 474
and templates, 647before type checking, 269, 593
multiple inheritance, 738class member declaration, 447class member definition, 448, 450class member definition, examples,
449collisions under inheritance, 591depends on static type, 590
multiple inheritance, 735inheritance, 590, 595local class, 797multiple inheritance, 737
ambiguous names, 738namespace names, 724
argument-dependent lookup, 726nested class, 791overloaded virtual functions, 593virtual inheritance, 743
name resolution, see name lookupnamespace, 8, 29, 712, 750
class friend declaration scope, 727cplusplus_primer, 714definition, 712design, 714discontiguous definition, 714function matching, 727global, 716member, 713member definition, 716
outside namespace, 716restrictions, 716
nested, 717scope, 713–717unnamed, 718
local to file, 718replace file static, 719
namespace keyword, 712namespace alias, 720, 750namespace pollution, 712, 750naming convention
header file, 264source file, 264
NDEBUG, 220negate<T>, 534negator, 535, 553nested class, 786, 806
access control, 787class defined outside enclosing class,
789in class template, 788in local class, 797member defined outside class body,
788name lookup, 791QueueItem example, 787relationship to enclosing class, 787,
790scope, 786static members, 790union, 794
nested namespace, 717nested type, see nsted class786new, 145, 174, 189, 806
compared to operator new, 760execution flow, 760
Index 869
header, 219member operator, 806member operator, interface, 764placement, 761, 807
compared to construct, 762new [], 135new failure, 175next_permutation, 821noboolalpha manipulator, 827NoDefault, 459nonconst reference, 60
parameter, 232limitations, 235
nonportable, 42nonprintable character, 40, 75nonreference
parameter, 230uses copy constructor, 478
return type, 247uses copy constructor, 478
nontype template parameter, 625, 628, 632,684
see also template parameterclass template, 655must be constant expression, 633
nonvirtual function, calls resolved at com-pile time, 569
noshowbase manipulator, 828noshowpoint manipulator, 832noskipws manipulator, 833not equal, see inequalitynot1, 535not2, 535not_equal_to<T>, 534NotQuery, 609
definition, 616eval function, 620
nouppercase manipulator, 828nth_element, 818NULL, 118null pointer, 118
delete of, 176null statement, 192, 224null-terminated array, see C-style stringnumber, magic, 56, 75numeric header, 395numeric literal
float (numF or numf), 39long (numL or numl), 39long double (ddd.dddL or ddd.dddl),
39
unsigned (numU or numu), 39
Oobject, 46, 75
automatic, 255, 280function, 553is not polymorphic, 569local static, 255, 281temporary, 247
object cleanup, see destructorobject creation
constructor, 452order of construction, 456
derived objects, 581, 582multiple base classes, 732virtual base classes, 745
order of destruction, 485derived objects, 587multiple base classes, 733virtual base classes, 747
object file, 68object lifetime, 254, 281
and destructor, 485compared to scope, 254
object-oriented programming, 285, 302, 622key ideas in, 558–560
oct manipulator, 827octal, literal (0num), 38octal escape sequence (\nnn), 40off-the-end iterator, 97, 394, 425
istream_iterator, 408off-the-end pointer, 125ofstream, 285, 293–299
see also ostreamclose, 294constructor, 293file marker, 838file mode, 296
combinations, 298example, 299
file random access, 838off_type, 839open, 293pos_type, 839random IO sample program, 840seek and tell members, 838–842
open, 293open_file, example of, 370, 383open_file program, 299operand, 148, 189
870 Index
order of evaluationcomma operator, 172conditional operator, 172logical operator, 172
operator, 148, 189sizeof, 167typeid, 775, 807addition (+), 150string, 86iterator, 101, 313pointer, 123
address-of (&), 115arrow (->), 164
class member access, 445assignment (=), 13, 30, 159
and conversion, 179and equality, 161container, 328multiple inheritance, 737pointer, 120string, 86to signed, 37to unsigned, 37yields lvalue, 160
binary, 148, 188bitwise AND (&), 156bitwise exclusive or (^), 156bitwise not (~), 155bitwise OR (|), 156bitwise OR (|), example, 290call (()), 30, 226comma (,), 168
operand order of evaluation, 172comma (,), example, 289compound assginment (e.g.,+=), it-
erator, 313compound assignment (e.g.,+=), 13,
30, 161string, 86arithmetic, 162bitwise, 162
conditional (?:), 165operand order of evaluation, 172
decrement (--)iterator, 312prefix yields lvalue, 162reverse iterator, 412
dereference (*), 98and increment, 163iterator, 98on map yields pair, 362
pointer, 119yields lvalue, 99, 120
division (/), 150dot (.), 25, 30
class member access, 445equality (==), 30, 154string, 85algorithm, 421container, 322container adaptor, 350iterator, 98, 312string, 347
greater-than (>), 30, 153greater-than-or-equal (>=), 30, 153increment (++), 13, 30
and dereference, 163iterator, 98, 312pointer, 114prefix yields lvalue, 162reverse iterator, 412
inequality (!=), 30, 154container, 322container adaptor, 350iterator, 98, 312string, 347
input (>>), 8, 30Sales_item, 516istream_iterator, 408string, 81precedence and associativity, 158
left-shift (<<), 155, 190less-than (<), 30, 153
used by algorithm, 420less-than-or-equal (<=), 13, 30, 153logical AND (&&), 152
operand order of evaluation, 172logical NOT (!), 153logical OR (||), 152
operand order of evaluation, 172modulus (%), 151multiplication (*), 150output (<<), 7, 30bitset, 106ostream_iterator, 408string, 81precedence and associativity, 158
overloaded, 189, 482, 503pointer to member
arrow (->*), 783dot (.*), 783
right-shift (>>), 155, 190
Index 871
scope (::), 8, 30, 78class member, 85, 445container defined type, 317member function definition, 262to override name lookup, 449
shift, 155, 190sizeof, 167subscript ([ ])bitset, 105deque, 325map, 363string, 87vector, 94, 325and multi-dimensioned array, 142and pointer, 124array, 113valid subscript range, 88yields lvalue, 88
subtraction (-), 150iterator, 101, 313pointer, 123
unary, 148, 189unary minus (-), 150unary plus (+), 150
operator alternative name, 46operator delete function, 760, 806
compared to deallocate, 761compared to delete expression, 760
operator delete member, 764and inheritance, 764example, 769CachedObj, 770interface, 764
operator delete [] member, 765operator new function, 760, 806
compared to allocate, 761compared to new expression, 760
operator new member, 764example, 769CachedObj, 769interface, 764
operator new [] member, 765operator overloading, see overloaded op-
eratoroptions to main, 243order of construction, 456, 749
derived objects, 581, 582multiple base classes, 732virtual base classes, 746
order of destruction, 485, 749derived objects, 587
multiple base classes, 733virtual base classes, 747
order of evaluation, 149, 189comma operator, 172conditional operator, 172logical operator, 172
ordering, strict weak, 360, 389OrQuery, 609
definition, 618eval function, 619
ostream, 6, 29, 285see also manipulatorcondition state, 287floatfield member, 831flushing output buffer, 290format state, 825inheritance hierarchy, 740no containers of, 310no copy or assign, 287not flushed if program crashes, 292output (<<), 7
precedence and associativity, 158precision member, 829seek and tell members, 838tie member, 292unsetf member, 831
ostream_iterator, 407, 425and class type, 410constructors, 408limitations, 411operations, 410output iterator, 417output operator (<<), 408used with algorithms, 411
ostringstream, 285, 299–301see also ostreamstr, 301
out (file mode), 296out_of_range, 219, 325out_of__stock, 699output, standard, 6output (<<), 7, 30
bitset, 106ostream_iterator, 408string, 81, 108overloaded operator, 513
formatting, 514must be nonmember, 514
precedence and associativity, 158Sales_item, 514
output iterator, 416, 425
872 Index
overflow, 150overflow_error, 219overload resolution, see function match-
ingoverloaded function, 265, 281
using declarations, 728using directive, 729compared to redeclaration, 266compared to template specialization,
673friend declaration, 467linkage directive, 803namespaces, 727scope, 268virtual, 593
overloaded member function, 436on const, 442
overloaded operator, 189, 482, 503<< (output operator), 513* (dereference), 524& (address-of), 511-> (arrow operator), 525[ ] (subscript), 522
reference return, 522() (call operator), 530= (assignment), 476, 483, 520
and copy constructor, 484check for self-assignment, 490Message, 490reference return, 483, 521rule of three, 485use counting, 495, 498valuelike classes, 501
>> (input operator), 515error handling, 516–517must be nonmember, 514
<< (output operator)formatting, 514must be nonmember, 514Sales_item, 514
&& (logical AND), 511|| (logical OR), 511, (comma operator), 511addition (+), Sales_item, 517ambiguous, 550arithmetic operators, 517as virtual function, 615binary operator, 508candidate functions, 549compound assignment (e.g.,+=), 511Sales_item, 521
consistency between relational andequality operators, 520
definition, 482, 506design, 510–513equality operators, 512, 518explicit call to, 509explicit call to postfix operators, 529function matching, 547–551member and this pointer, 483member vs. nonmember function,
508, 512postfix increment (++) and decrement
(--) operators, 528precedence and associativity, 507prefix increment (++) and decrement
(--) operators, 527relational operators, 511, 520require class-type parameter, 507unary operator, 508
overloading, see overloaded functionoperator, see overloaded operator
Ppair, 356, 388
as return type from map::insert,365
as return type from set::insert,373
default constructor, 357definition, 356initialization, 356make_pair, 358operations, 357public data members, 357
Panda, 731virtual inheritance, 741
parameter, 226, 227, 281array and buffer overflow, 242array type, 238–244C-style string, 242const, 231const reference, 235
overloading, 275ellipsis, 244function pointer, 278
linkage directive, 804initialization of, 229iterator, 238, 242library container, 237lifetime, 255
Index 873
local copy, 230matching, 229
ellipsis, 244template specialization, 673with class type conversion, 541
multi-dimensioned array, 241nonconst reference, 232nonreference type, 230
uses copy constructor, 478of member function, 260vector type, 237passing, 229pointer to const, 231
overloading, 275pointer to function, 278
linkage directive, 804pointer to nonconst, 231pointer type, 231, 239reference
to array type, 240to pointer, 236
template, see template parameterand main, 243type checking
and template argument, 638of reference to array, 240
parameter list, 3, 29, 226, 228member function definition, 446
parentheses, override precedence, 169partial specialization, 678, 684partial_sort, 818partial_sort_copy, 818partial_sum, 824partition, 817placement new, 761, 807
compared to construct, 762plus<T>, 534pointer, 114, 114–126, 146
array, 122arrow (->), 164as initializer of vector, 140as parameter, 231assignment, 120char*, see C-style stringclass member copy control, 492–501
copy constructor, 480destructor, 485strategies, 499
compared to iterator, 114compared to reference, 121const, 128
const pointer to const, 129container constructor from, 308conversion from derived to base, 567conversion from derived to multiple
base, 734conversion to bool, 182conversion to void, 181dangling, 176, 188
synthesized copy control, 494declaration style, 116–117definition, 115delete, 176dynamic_cast, example, 773function returning, 228implicit this, 260, 281initialization, 117–119is polymorphic, 569multi-dimensioned array, 143new, 174null, 118off-the-end, 125pitfalls with generic programs, 671reference parameter, 236relational operator, 132return type and local variable, 249smart, 495, 503, 553
handle class, 599overloaded-> (arrow operator) and* (dereference), 524
overloaded (++) and (*), 526subscript operator, 124to pointer, 122typedef, 129typeid operator, 776uninitialized, 117volatile, 800
pointer arithmetic, 123, 146pointer to const, 127
argument, 231conversion from nonconst, 127parameter, 231
overloading, 275pointer to function, 276–279
definition, 276exception specifications, 711function returning, 228initialization, 277linkage directive, 803overloaded functions, 279parameter, 278return type, 278
874 Index
typedef, 276pointer to member, 780, 807
and typedef, 783arrow (->*), 783definition, 781dot (.*), 783function pointer, 782function table, 785
pointer to nonconstargument, 231parameter, 231
polymorphism, 558, 622compile time polymorphism via tem-
plates, 624run time polymorphism in C++, 569
poppriority_queue, 352queue, 352stack, 351
pop_back, sequential container, 326pop_front, sequential container, 326portable, 797postfix decrement (--)
overloaded operator, 528yields rvalue, 163
postfix increment (++)and dereference, 163overloaded operator, 528
precedence, 124, 146, 149, 168, 189of assignment, 160of conditional, 166of dot and derefernece, 164of increment and dereference, 163of IO operator, 158of pointer to member and call oper-
ator, 782overloaded operator, 507pointer parameter declaration, 241
precedence table, 170predicate, 402, 425prefix decrement (--), 163
overloaded operator, 527yields lvalue, 162
prefix increment (++)and dereference, 163overloaded operator, 527yields lvalue, 162
preprocessor, 70, 75directive, 7, 29macro, 221, 224variable, 71
prev_permutation, 821preventing copies of class objects, 481print_total, 559
explained, 568printable character, 88printValues program, 240, 242, 243priority_queue, 348, 354
constructors, 349relational operator, 350
privateclass, 496copy constructor, 481inheritance, 571member, 75, 474
private access label, 65, 432inheritance, 561
private inheritance, 622program
factorial, 250find_val, 234gcd, 226isShorter, 235make_plural, 248open_file, 299printValues, 240, 242, 243ptr_swap, 237rgcd, 250swap, 233, 245vector capacity, 331book finding
using equal_range, 379using find, 377using upper_bound, 378
bookstore, 26bookstore exception classes, 698CachedObj, 766duplicate words, 400–404
revisited, 531find last word, 414GT6, 403Handle class, 667int instantiation, 668operations, 668Sales_item instantiation, 669
isShorter, 403message handling classes, 486Query
design, 609–611interface, 610operations, 607
Queue, 648
Index 875
copy_elems member, 652destroy member, 651pop member, 651push member, 652
random IO example, 840restricted word count, 374Sales_item handle class, 599Screen class template, 655TextQuery, 383
class definition, 382design, 380interface, 381
vector, capacity, 331vowel counting, 200word count, 363word transformation, 370ZooAnimal class hierarchy, 731
programmer-defined header, 67–72programming
generic, 95, 624object-oriented, 285, 302, 622
promotion, integral, 180, 189protected, inheritance, 571, 622protected access label, 562, 622protected keyword, 562prototype, function, 251, 281ptr_swap program, 237ptrdiff_t, 123, 146public
inheritance, 571, 622member, 75, 474
public access label, 65, 432inheritance, 561
pure virtual function, 596, 622example, 609
pushpriority_queue, 352queue, 352stack, 351
push_back, 94, 108vector, 94back_inserter, 399sequential container, 318
push_frontfront_inserter, 406sequential container, 318
put_Msg_in_Folder, 489
QQuery, 610
& (bitwise AND), 610definition, 614
~ (bitwise NOT), 610definition, 614
| (bitwise OR), 610definition, 614
<< (output operator), 615definition, 613design, 609–611interface, 610operations, 607
Query_base, 609definition, 612member functions, 609
Queue<< (output operator), 659assign, 662copy_elems member, 652, 662definition, 648design, 647destroy member, 651final class definition, 664interface, 627member template declarations, 661operations, 627pop member, 651push, specialized, 677push member, 652template version, char*, 675
queue, 348, 354constructors, 349relational operator, 350
QueueItem, 648as nested class, 787
constructor, 789definition, 788
friendship, 658CachedObj, 768
allocation explained, 769
RRaccoon as virtual base, 741RAII, see resource allocation is initializa-
tionraise, 750raise exception, see throwrandom file IO, 838random-access iterator, 417, 425
deque, 417string, 417
876 Index
vector, 417random_shuffle, 820range
iterator, 314, 314–316, 354left-inclusive, 314
range_error, 219rbegin, container, 317, 412rdstate, 290recursive function, 249, 281refactoring, 583, 622referece, 317reference, 58, 75
and pointer, 121const reference, 59
initialization, 60conversion from derived to base, 567conversion from derived to multiple
base, 734dynamic_cast operator, example,
774is polymorphic, 569nonconst reference, 60parameter, 232–237pointer parameter, 236return type, is lvalue, 249return type and class object, 440return type and local variable, 249return value, 248to array parameter, 240
reference count, see use countreference data member, initialization, 455reference to const, see const referencereinterpret_cast, 183, 185relational operator, 153
string, 85associative container, 359container, 321container adaptor, 350function object, 533overloaded operator, 511, 520
consistent with equality, 520pointer, 132
remove, 819list, 423
remove_copy, 820remove_copy_if, 820remove_if, 819
list, 423remove_Msg_from_Folder, 491rend, container, 317, 412replace, 400, 816
string, 342replace_copy, 400, 815replace_copy_if, 815replace_if, 816reserve
string, 336vector, 331
reserved identifier, 47resize, sequential container, 323Resource, 700resource allocation is initialization, 700–
701auto_ptr, 702
restricted word count program, 374result, 148, 189rethrow, 695, 750return, container, 381return statement, 245–251
from main, 247implicit, 245local variable, 247, 249
return type, 3, 29, 226, 227const reference, 249function, 281function pointer, 278linkage directive, 804member function definition, 446no implicit return type, 228nonreference, 247
uses copy constructor, 478of virtual function, 564pointer to function, 278reference, 248reference yields lvalue, 249void, 245
return valueconversion, 246copied, 247
reverse, 819list, 423
reverse iterator, 405, 412–415, 425-- (decrement), 412++ (increment), 412base, 414compared to iterator, 413, 414example, 414requires -- (decrement), 413
reverse_copy, 819reverse_iterator, 412
container, 316rfind, string, 346
Index 877
rgcd program, 250right manipulator, 832right-shift (>>), 155, 190rotate, 819rotate_copy, 820rule of three, 485, 503
exception for virtual destructors, 588run time, 75
error, 38run-time type identification, 772–780, 807
classes with virtual functions, 772compared to virtual functions, 777dynamic_cast, 773
example, 773throws bad_cast, 774to poiner, 773to reference, 774
type-sensitive equality, 778typeid, 775
and virtual functions, 775example, 776returns type_info, 776
runtime_error, 217, 219constructor from string, 218
rvalue, 45, 75
Ssafety, exception, 700Sales_item, 21
addition (+), 23, 517throws exception, 217, 699
class definition, 64, 258–265compare function, 604compound assignment (e.g.,+=), 521conversion, 461default constructor, 263equality operators (==), (!=), 519explicit constructor, 462handle class, 599clone function, 602constructor, 601, 602definition, 600design, 599multiset of, 605using generic Handle, 669
header, 21, 67, 264input (>>), 516istream constructor, 452no relational operators, 520operations, 21
output (<<), 514avg_price definition, 261same_isbn, 24, 258string constructor, 452
scientific manipulator, 830scope, 54, 75
const object, 57, 69block, 193class, 65, 444, 473compared to object lifetime, 254for statement, 15friend declaration, 466function, 227function template specialization, 674global, 54, 74local, 54, 75multiple inheritance, 737namespace, 713–717statement, 194template parameter, 629using declaration, 720using directive, 721
example, 722name collisions, 723
scope (::)base class members, 569namespace member, 750
scope operator (::), 8, 30, 78, 108class member, 85, 445container defined type, 317member function definition, 262namespace member, 713to override class-specific memory al-
location, 765to override name lookup, 449
Screen, 435class template, 655concatenating operations, 441display, 442do_display, 442friends, 465get definition, 446get members, 436get_cursor definition, 446CachedObj, 768Menu function table, 785move members, 441set members, 441simplified, 781size_type, 435
ScreenPtr, 523
878 Index
arrow operator (->), 525dereference (*), 524use counted, 523
ScrPtr, 523search, 813search_n, 813self-assignment
auto_ptr, 705check, 490use counting, 498
semantics, value, 499, 503semicolon (;), 3semicolon (;), class definition, 440sentinel, 97, 108separate compilation, 67, 76
inclusion model for templates, 644of templates, 643separate compilation model for tem-
plates, 645, 684sequence, escape, 74sequence (\Xnnn), hexadecimal escape, 40sequential container, 306, 354
assign, 328assignment (=), 328back, 324clear, 327const_iterator, 316const_reverse_iterator, 316constructor from element count
uses copy constructor, 478uses element default constructor,
460constructors, 307–309deque, 306element type constraints, 309, 323empty, 323erase, 326front, 324insert, 319iterator, 316list, 306operations, 316–330performance characteristics, 333pop_back, 326pop_front, 326priority_queue, 348push_back, 318push_front, 318queue, 348rbegin, 412rend, 412
resize, 323returning a, 381reverse_iterator, 316, 412size, 323size_type, 316stack, 348supports relational operators, 321swap, 329types defined by, 316value_type, 317vector, 306
set, 356, 388as element type, 311assignment (=), 328begin, 372bidirectional iterator, 417clear, 359constructors, 372count, 372element type constraints, 309empty, 359end, 372equal_range, 379erase, 359, 372find, 372insert, 373iterator, 374key type constraints, 360lower_bound, 377operations, 358overriding the default comparison,
604rbegin, 412rend, 412return alternatives, 381return type from insert, 373reverse_iterator, 412size, 359supports relational operators, 359swap, 329upper_bound, 377value_type, 372
set_difference, 822set_intersection, 619, 822set_symmetric_difference, 822set_union, 822setfill manipulator, 832setprecision manipulator, 829setstate, 289, 290setw manipulator, 832shift operator, 155, 190
Index 879
short, 34short-circuit evaluation, 152
overloaded operator, 508shorterString, 248showbase manipulator, 827showpoint manipulator, 831signed, 35, 76
conversion to unsigned, 36, 180size, 108
string, 83vector, 93associative container, 359priority_queue, 352queue, 352sequential container, 323stack, 351
size_t, 104, 108, 146and array, 113
size_type, 84, 108string, 84vector, 93container, 316
sizeof operator, 167skipws manipulator, 833sliced, 579, 622SmallInt, 536, 550
conversion operator, 537smart pointer, 495, 503, 553
handle class, 599overloaded -> (arrow operator) and
* (dereference), 524overloaded (++) and (*), 526
sort, 401, 817source file, 4, 29
naming convention, 264specialization
class templatedefinition, 675member defined outside class body,
676partial, 678partial specialization, 684
class template member, 677declaration, 677
function templatecompared to overloaded function,
673declaration, 672, 673example, 672scope, 674
template, namespaces, 730
specifier, type, 48, 76splice, list, 423sstream
header, 285, 300str, 301
stable_partition, 817stable_sort, 403, 817stack, 348, 354
constructors, 349relational operator, 350
stack unwinding, 691, 750standard error, 6, 29standard input, 6, 29standard library, 5, 29standard output, 6, 30state, condition, 302statement, 2, 30
break, 212, 223continue, 214, 223do while, 210for, 29, 207goto, 214, 224if, 17, 29, 195, 224return, 245–251switch, 199, 224while, 12, 30, 204, 224compound, 193, 223declaration, 193, 224expression, 192, 224for statementfor, 14labeled, 214, 224null, 192, 224return, local variable, 247, 249
statement block, see blockstatement label, 214statement scope, 194statementfor statement, for, 14static (file static), 719static class member, 467, 474
as default argument, 471class template, 665
accessed through an instantiation,666
definition, 666const data member, initialization,
470const member function, 469data member, 469
as constant expression, 471inheritance, 576member function, 467
880 Index
this pointer, 469static object, local, 255, 281static type, 568, 622
determines name lookup, 590multiple inheritance, 735
static type checking, 44, 76argument, 229function return value, 246
static_cast, 183, 185std, 8, 30stdexcept header, 217, 219store, free, 135, 145str, 301strcat, 133strcmp, 133strcpy, 133stream
istream_iterator, 407ostream_iterator, 407flushing buffer, 290iterator, 405, 407–412
and class type, 410limitations, 411used with algorithms, 411
not flushed if program crashes, 292type as condition, 19
stream iterator, 425strict weak ordering, 360, 389string, C-style, see C-style stringstring, 80–89
addition, 86addition to string literal, 87and string literal, 81, 140append, 342are case sensitive, 344as sequential container, 335assign, 340assignment (=), 86c_str, 140c_str, example, 294capacity, 336compare, 347compared to C-style string, 134compound assignment, 86concatenation, 86constructor, 80, 338–339default constructor, 52empty, 83equality (==), 85equality operator, 347erase, 340
find, 344find_first_not_of, 346find_first_of, 345find_last_not_of, 346find_last_of, 346getline, 82getline, example, 300header, 80input operation as condition, 82input operator, 81insert, 340output operator, 81random-access iterator, 417relational operator, 85, 347replace, 342reserve, 336rfind, 346size, 83size_type, 84subscript operator, 87substr, 342
string literal, 9, 30, 40addition to string, 87and string library type, 81, 140and C-style string, 140concatenation, 41
stringstream, 285, 299–301, 302see also istreamsee also ostreamstr, 301
strlen, 133strncat, 133strncpy, 133struct, see also class
default access label, 433default inheritance access label, 574
struct, keyword, 66, 76, 474in variable definition, 440
structure, data, 20, 28Studio, Visual, 4subscript ([ ]), 87, 108, 146, 389
bitset, 105deque, 325map, 363string, 87vector, 94, 325and multi-dimensioned array, 142and pointer, 124array, 113overloaded operator, 522
reference return, 522
Index 881
valid subscript range, 88yields lvalue, 88
subscript rangestring, 88vector, 96array, 114
substr, string, 342subtraction (-), 150
iterator, 101, 313pointer, 123
swap, 329, 816container, 329
swap program, 233, 245swap_ranges, 816switch statement, 199, 224
default label, 203and break, 201–203case label, 201compared to if, 199execution flow, 201expression, 203variable definition, 204
synthesized assignment (=), 483, 503multiple inheritance, 737pointer members, 493
synthesized copy constructor, 479, 503multiple inheritance, 737pointer members, 493virtual base class, 747
synthesized copy control, volatile, 800synthesized default constructor, 264, 281,
459, 474inheritance, 581
synthesized destructor, 485, 486multiple inheritance, 737pointer members, 493
T\t (tab character), 40table of library name and header, 810template
see also class templatesee also function templatesee also instantiationclass, 90, 107class member, see member templatelink time errors, 635overview, 624
template keyword, 625template argument, 625, 684
and function argument type check-ing, 638
class template, 628conversion, 638deduction, 684
from function pointer, 640deduction for class template mem-
ber function, 653deduction for function template, 637explicit and class template, 636explicit and function template, 642
and function pointer, 643specifying, 642
pointer, 671template argument deduction, 637template class, see class templatetemplate function, see function templatetemplate parameter, 625, 628–633, 684
and member templates, 663name, 628
restrictions on use, 629nontype parameter, 625, 628, 632, 684
class template, 655must be constant expression, 633
scope, 629type parameter, 625, 628, 630, 684uses of inside class definition, 649
template parameter list, 625, 684template specialization, 672, 684
class member declaration, 677compared to overloaded function, 673definition, 675example, 672function declaration, 672, 673member defined outside class body,
676member of class template, 677parameter matching, 673partial specialization, 678, 684scope, 674
template<>, see template specializationtemporary object, 247terminate, 219, 219, 224, 692, 750TextQuery
class definition, 382main program using, 383program design, 380program interface, 381revisited, 609
this pointerimplicit, 260, 281
882 Index
implicit parameter, 431, 440in overloaded operator, 483overloaded operator, 508static member functions, 469
three, rule of, 485, 503throw, 216, 216, 224, 689, 750
example, 217, 290execution flow, 218, 691pointer to local object, 690rethrow, 695
tolower, 88top
priority_queue, 352stack, 351
toupper, 88transform, 815transformation program, word, 370translation unit, see source filetrunc (file mode), 296try block, 216, 217, 224, 750try keyword, 217type
abstract data, 78, 473arithmetic, 34, 73built-in, 3, 28, 34–37class, 20, 28, 65compound, 58, 73, 145dynamic, 568, 622function return, 281incomplete, 438, 474integral, 34, 75library, 29nested, see nsted class786return, 3, 29, 226, 227static, 568, 622
determines name lookup, 590name lookup and multiple inher-
itance, 735type checking, 44
argument, 229with class type conversion, 541
ellipsis parameter, 244name lookup, 269reference to array argument, 240
type identification, run-time, 772–780, 807type specifier, 48, 76type template parameter, 628, 630, 684
see also template parametertype_info, 807
header, 219name member, 780
no copy or assign, 780operations, 779returned from typeid, 776
typedefand pointer, 129and pointer to member, 783pointer to function, 276
typedef, 61, 76typeid operator, 775, 807
and virtual functions, 775example, 776returns type_info, 776
typename, keywordcompared to class, 631in template parameter, 630inside template definition, 632
UU_Ptr, 496unary function object, 533unary minus (-), 150unary operator, 148, 189unary plus (+), 150uncaught exception, 692undefined behavior, 41, 76
dangling pointer, 176synthesized copy control, 494
invalidated iterator, 315uninitialized class data member, 459uninitialized pointer, 117uninitialized variable, 51
underflow_error, 219unexpected, 708, 750uninitialized, 8, 30, 51, 76uninitialized pointer, 117uninitialized_copy, 755, 759uninitialized_fill, 755union, 792, 807
anonymous, 795, 805as nested type, 794example, 794limitations on, 793
union keyword, 793unique, 402, 819
list, 423unique_copy, 412, 820unitbuf, manipulator flushes the buffer,
291unnamed namespace, 718, 750
local to file, 718
Index 883
replace file static, 719unsigned, 35, 76
conversion to signed, 36, 180literal (numU or numu), 39
unsigned char, 36unwinding, stack, 691, 750upper_bound, 814
associative container, 377book finding program, 378example, 607
uppercase manipulator, 828use count, 495, 503
design overview, 495generic class, 667held in companion class, 496pointer to, 600self-assignment check, 498
user, 433, 563using declaration, 78, 108, 720, 750
access control, 573class member access, 574in header, 80overloaded function, 728overloaded inherited functions, 593scope, 720
using directive, 721, 751overloaded function, 729pitfalls, 724scope, 721
example, 722name collisions, 723
utility header, 356
Vvalue initialization, 92, 108
map subscript operator, 363vector, 92and dynamically allocated array, 136dequedeque, 309listlist, 309of dynamically allocated object, 175and resize, 324sequential container, 309vectorvector, 309
value semantics, 499, 503value_type, 389
map, multimap, 361sequential container, 317set, multiset, 372
varargs, 244
variable, 8, 30, 43–55define before use, 44defined after case label, 204definition, 48definitions and goto, 215initialization, 48, 50, 76
constructor, 452local, 227, 281scope, 55
Vector, 757capacity, 757memory allocation strategy, 757push_back, 758reallocate, 758size, 757using operator new and delete,
761using explicit destructor call, 763using placement new, 762
vector, 90–95, 354argument, 237as element type, 311assign, 328assignment (=), 328at, 325back, 324begin, 97, 317capacity, 331clear, 327const_iterator, 99, 316const_reference, 317const_reverse_iterator, 316constructor from element count, uses
copy constructor, 478constructor taking iterators, 140constructors, 91–92, 307–309difference_type, 316element type constraints, 309, 323empty, 93, 323end, 97, 317erase, 326, 402
invalidates iterator, 326front, 324header, 90initialization from pointer, 140insert, 319
invalidates iterator, 320iterator, 97, 316iterator supports arithmetic, 312memory allocation strategy, 756memory management strategy, 330
884 Index
parameter, 237performance characteristics, 334pop_back, 326push_back, 94, 318
invalidates iterator, 321random-access iterator, 417rbegin, 317, 412reference, 317relational operators, 321rend, 317, 412reserve, 331resize, 323reverse_iterator, 316, 412size, 93, 323size_type, 93, 316subscript ([ ]), 325subscript operator, 94supports relational operators, 313swap, 329type, 91types defined by, 316value_type, 317
vector capacity program, 331viable function, 270, 282
with class type conversion, 545virtual base class, 741, 751
ambiguities, 743conversion, 743defining base as, 742derived class constructor, 744name lookup, 743order of construction, 746stream types, 741
virtual function, 559, 566–570, 622assignment operator, 588calls resolved at run time, 568compared to run-time type identifi-
cation, 777default argument, 570derived classes, 564destructor, 587
multiple inheritance, 736exception specifications, 710in constructors, 589in destructor, 589introduction, 561multiple inheritance, 735no virtual constructor, 588overloaded, 593overloaded operator, 615overriding run-time binding, 570
pure, 596, 622example, 609
return type, 564run-time type identification, 772scope, 594static, 469to copy unknown type, 602type-sensitive equality, 778
virtual inheritance, 741, 751virtual keyword, 559Visual Studio, 4void, 34, 76
return type, 245void*, 119, 146
const void*, 127, 145volatile, 800, 807
pointer, 800synthesized copy control, 800
vowel counting program, 200
Wwcerr, 286wchar_t, 34
literal, 40wchar_t streams, 286wcin, 286wcout, 286weak ordering, strict, 360, 389wfstream, 286what, see exceptionwhile statement, 12, 30, 204, 224
condition in, 205whitespace, 81wide character streams, 286wifstream, 286window, console, 6Window_Mgr, 465wiostream, 286wistream, 286wistringstream, 286wofstream, 286word, 35, 76word count program, 363
restricted, 374word per line processing
istringstream, 386istringstreamistringstream, 370
istringstream, 300word transformation program, 370WordQuery, 609
Index 885
definition, 616wostream, 286wostringstream, 286wrap around, 38wstringstream, 286
X\Xnnn (hexadecimal escape sequence), 40
ZZooAnimal, using virtual inheritance, 741ZooAnimal class hierarchy, 731