introductiontoc++programming, input/output and operators · the input/output stream header.this...

40
2 Introduction to C++ Programming, Input/Output and Operators Objectives In this chapter you’ll: Write simple C++ programs. Write input and output statements. Use fundamental types. Use arithmetic operators. Learn the precedence of arithmetic operators. Write decision-making statements.

Upload: others

Post on 21-May-2020

33 views

Category:

Documents


1 download

TRANSCRIPT

2Introduction to C++ Programming,

Input/Output and Operators

O b j e c t i v e sIn this chapter you’ll:

� Write simple C++ programs.

� Write input and output statements.

� Use fundamental types.

� Use arithmetic operators.

� Learn the precedence of arithmetic operators.

� Write decision-making statements.

20 Chapter 2 Introduction to C++ Programming, Input/Output and OperatorsO

utl

ine

2.1 IntroductionWe now introduce C++ programming. We show how to display messages on the screenand obtain data from the user at the keyboard for processing. We explain how to performarithmetic calculations and save their results for later use. We demonstrate decision-makingby showing you how to compare two numbers, then display messages based on the com-parison results.

Compiling and Running ProgramsAt www.deitel.com/books/cpp11fp, we’ve posted videos that demonstrate compiling andrunning programs in Microsoft Visual C++, GNU C++ and Xcode.

2.2 First Program in C++: Printing a Line of TextConsider a simple program that prints a line of text (Fig. 2.1). This program illustrates sev-eral important features of the C++ language. The line numbers are not part of the sourcecode.

CommentsLines 1 and 2

each begin with //, indicating that the remainder of each line is a comment. The commentText-printing program describes the purpose of the program. A comment beginning with

2.1 Introduction2.2 First Program in C++: Printing a Line of

Text2.3 Modifying Our First C++ Program2.4 Another C++ Program: Adding Integers

2.5 Arithmetic2.6 Decision Making: Equality and

Relational Operators2.7 Wrap-Up

1 // Fig. 2.1: fig02_01.cpp2 // Text-printing program.3 #include <iostream> // allows program to output data to the screen45 // function main begins program execution6 int main()7 {8 std::cout << "Welcome to C++!\n"; // display message9

10 return 0; // indicate that program ended successfully11 } // end function main

Welcome to C++!

Fig. 2.1 | Text-printing program.

// Fig. 2.1: fig02_01.cpp// Text-printing program.

2.2 First Program in C++: Printing a Line of Text 21

// is called a single-line comment because it terminates at the end of the current line. [Note:You also may use comments containing one or more lines enclosed in /* and */.]

#include Preprocessing DirectiveLine 3

is a preprocessing directive, which is a message to the C++ preprocessor (introduced inSection 1.4). Lines that begin with # are processed by the preprocessor before the programis compiled. This line notifies the preprocessor to include in the program the contents ofthe input/output stream header <iostream>. This header is a file containing informationused by the compiler when compiling any program that outputs data to the screen or in-puts data from the keyboard using C++’s stream input/output. The program in Fig. 2.1outputs data to the screen, as we’ll soon see. We discuss headers in more detail inChapter 6 and explain the contents of <iostream> in Chapter 13.

Blank Lines and White SpaceLine 4 is simply a blank line. Together, blank lines, space characters and tab characters areknown as whitespace. Whitespace characters are normally ignored by the compiler.

The main FunctionLine 5

is another single-line comment indicating that program execution begins at the next line.Line 6

is a part of every C++ program. The parentheses after main indicate that main is a programbuilding block called a function. C++ programs typically consist of one or more functionsand classes (as you’ll learn in Chapter 3). Exactly one function in every program must benamed main. Figure 2.1 contains only one function. C++ programs begin executing atfunction main, even if main is not the first function defined in the program. The keywordint to the left of main indicates that main returns an integer value. The complete list ofC++ keywords can be found in Fig. 4.2. We’ll say more about return a value when wedemonstrate how to create your own functions in Section 3.3. For now, simply includethe keyword int to the left of main in each of your programs.

The left brace, {, (line 7) must begin the body of every function. A correspondingright brace, }, (line 11) must end each function’s body.

An Output StatementLine 8

#include <iostream> // allows program to output data to the screen

Common Programming Error 2.1Forgetting to include the <iostream> header in a program that inputs data from the key-board or outputs data to the screen causes the compiler to issue an error message.

// function main begins program execution

int main()

std::cout << "Welcome to C++!\n"; // display message

22 Chapter 2 Introduction to C++ Programming, Input/Output and Operators

instructs the computer to perform an action—namely, to print the characters containedbetween the double quotation marks. Together, the quotation marks and the charactersbetween them are called a string, a character string or a string literal. In this book, werefer to characters between double quotation marks simply as strings. Whitespace charac-ters in strings are not ignored by the compiler.

The entire line 8, including std::cout, the << operator, the string "Welcome to

C++!\n" and the semicolon (;), is called a statement. Most C++ statements end with asemicolon, also known as the statement terminator (we’ll see some exceptions to thissoon). Preprocessing directives (like #include) do not end with a semicolon. Typically,output and input in C++ are accomplished with streams of characters. Thus, when thepreceding statement is executed, it sends the stream of characters Welcome to C++!\n tothe standard output stream object—std::cout—which is normally “connected” to thescreen.

The std NamespaceThe std:: before cout is required when we use names that we’ve brought into the pro-gram by the preprocessing directive #include <iostream>. The notation std::cout spec-ifies that we are using a name, in this case cout, that belongs to namespace std. The namescin (the standard input stream) and cerr (the standard error stream)—introduced inChapter 1—also belong to namespace std. Namespaces are an advanced C++ feature thatwe discuss in depth in Chapter 21, Other Topics. For now, you should simply rememberto include std:: before each mention of cout, cin and cerr in a program. This can becumbersome—the next example introduces using declarations and the using directive,which will enable you to omit std:: before each use of a name in the std namespace.

The Stream Insertion Operator and Escape SequencesIn the context of an output statement, the << operator is referred to as the stream insertionoperator. When this program executes, the value to the operator’s right, the right operand,is inserted in the output stream. Notice that the operator points in the direction of wherethe data goes. A string literal’s characters normally print exactly as they appear between thedouble quotes. However, the characters \n are not printed on the screen (Fig. 2.1). Thebackslash (\) is called an escape character. It indicates that a “special” character is to beoutput. When a backslash is encountered in a string of characters, the next character iscombined with the backslash to form an escape sequence. The escape sequence \n meansnewline. It causes the screen cursor to move to the beginning of the next line on the screen.Some common escape sequences are listed in Fig. 2.2.

Good Programming Practice 2.1Indent the body of each function one level within the braces that delimit the function’sbody. This makes a program’s functional structure stand out and makes the program easierto read.

Good Programming Practice 2.2Set a convention for the size of indent you prefer, then apply it uniformly. The tab keymay be used to create indents, but tab stops may vary. We prefer three spaces per level ofindent.

2.3 Modifying Our First C++ Program 23

The return StatementLine 10

is one of several means we’ll use to exit a function. When the return statement is used atthe end of main, as shown here, the value 0 indicates that the program has terminated suc-cessfully. The right brace, }, (line 11) indicates the end of function main. According to theC++ standard, if program execution reaches the end of main without encountering a re-turn statement, it’s assumed that the program terminated successfully—exactly as whenthe last statement in main is a return statement with the value 0. For that reason, we omitthe return statement at the end of main in subsequent programs.

2.3 Modifying Our First C++ ProgramWe now present two examples that modify the program of Fig. 2.1 to print text on one lineby using multiple statements and to print text on several lines by using a single statement.

Printing a Single Line of Text with Multiple StatementsWelcome to C++! can be printed several ways. For example, Fig. 2.3 performs stream inser-tion in multiple statements (lines 8–9), yet produces the same output as the program ofFig. 2.1. [Note: From this point forward, we use a light gray background to highlight thekey features each program introduces.] Each stream insertion resumes printing where theprevious one stopped. The first stream insertion (line 8) prints Welcome followed by aspace, and because this string did not end with \n, the second stream insertion (line 9) be-gins printing on the same line immediately following the space.

Escapesequence Description

\n Newline. Position the screen cursor to the beginning of the next line.\t Horizontal tab. Move the screen cursor to the next tab stop.\r Carriage return. Position the screen cursor to the beginning of the

current line; do not advance to the next line.\a Alert. Sound the system bell.\\ Backslash. Used to print a backslash character.\' Single quote. Used to print a single quote character.\" Double quote. Used to print a double quote character.

Fig. 2.2 | Escape sequences.

return 0; // indicate that program ended successfully

1 // Fig. 2.3: fig02_03.cpp2 // Printing a line of text with multiple statements.3 #include <iostream> // allows program to output data to the screen4

Fig. 2.3 | Printing a line of text with multiple statements. (Part 1 of 2.)

24 Chapter 2 Introduction to C++ Programming, Input/Output and Operators

Printing Multiple Lines of Text with a Single StatementA single statement can print multiple lines by using newline characters, as in line 8 ofFig. 2.4. Each time the \n (newline) escape sequence is encountered in the output stream,the screen cursor is positioned to the beginning of the next line. To get a blank line in youroutput, place two newline characters back to back, as in line 8.

2.4 Another C++ Program: Adding IntegersOur next program obtains two integers typed by a user at the keyboard, computes the sumof these values and outputs the result using std::cout. Figure 2.5 shows the program andsample inputs and outputs. In the sample execution, we highlight the user’s input in bold.The program begins execution with function main (line 6). The left brace (line 7) beginsmain’s body and the corresponding right brace (line 22) ends it.

5 // function main begins program execution6 int main()7 {89

10 } // end function main

Welcome to C++!

1 // Fig. 2.4: fig02_04.cpp2 // Printing multiple lines of text with a single statement.3 #include <iostream> // allows program to output data to the screen45 // function main begins program execution6 int main()7 {8 std::cout << "Welcome to C++!\n";9 } // end function main

Welcometo

C++!

Fig. 2.4 | Printing multiple lines of text with a single statement.

1 // Fig. 2.5: fig02_05.cpp2 // Addition program that displays the sum of two integers.3 #include <iostream> // allows program to perform input and output

Fig. 2.5 | Addition program that displays the sum of two integers. (Part 1 of 2.)

Fig. 2.3 | Printing a line of text with multiple statements. (Part 2 of 2.)

std::cout << "Welcome ";std::cout << "to C++!\n";

\n \n\n

2.4 Another C++ Program: Adding Integers 25

Variable DeclarationsLines 9–11

are declarations. The identifiers number1, number2 and sum are the names of variables.These declarations specify that the variables number1, number2 and sum are data of typeint, meaning that these variables will hold integer values. The declarations also initializeeach of these variables to 0.

All variables must be declared with a name and a data type before they can be used in aprogram. Several variables of the same type may be declared in one declaration or in mul-tiple declarations. We could have declared all three variables in one declaration by using acomma-separated list as follows:

This makes the program less readable and prevents us from providing comments that de-scribe each variable’s purpose.

45 // function main begins program execution6 int main()7 {8 // variable declarations9

10111213 std::cout << "Enter first integer: "; // prompt user for data141516 std::cout << "Enter second integer: "; // prompt user for data1718192021 std::cout << "Sum is " << sum << ; // display sum; end line22 } // end function main

Enter first integer: 45Enter second integer: 72Sum is 117

int number1 = 0; // first integer to add (initialized to 0)int number2 = 0; // second integer to add (initialized to 0)int sum = 0; // sum of number1 and number2 (initialized to 0)

Error-Prevention Tip 2.1Although it’s not always necessary to initialize every variable explicitly, doing so will helpyou avoid many kinds of problems.

int number1 = 0, number2 = 0, sum = 0;

Fig. 2.5 | Addition program that displays the sum of two integers. (Part 2 of 2.)

int number1 = 0; // first integer to add (initialized to 0)int number2 = 0; // second integer to add (initialized to 0)int sum = 0; // sum of number1 and number2 (initialized to 0)

std::cin >> number1; // read first integer from user into number1

std::cin >> number2; // read second integer from user into number2

sum = number1 + number2; // add the numbers; store result in sum

std::endl

26 Chapter 2 Introduction to C++ Programming, Input/Output and Operators

Fundamental TypesWe’ll soon discuss the type double for specifying real numbers, and the type char for spec-ifying character data. Real numbers are numbers with decimal points, such as 3.4, 0.0 and–11.19. A char variable may hold only a single lowercase letter, a single uppercase letter,a single digit or a single special character (e.g., $ or *). Types such as int, double and charare called fundamental types. Fundamental-type names consist of one or more keywordsand therefore must appear in all lowercase letters. Appendix C contains the complete listof fundamental types.

IdentifiersA variable name (such as number1) is any valid identifier that is not a keyword. An identi-fier is a series of characters consisting of letters, digits and underscores ( _ ) that does notbegin with a digit. C++ is case sensitive—uppercase and lowercase letters are different, soa1 and A1 are different identifiers.

Placement of Variable DeclarationsDeclarations of variables can be placed almost anywhere in a program, but they must ap-pear before their corresponding variables are used in the program. For example, in the pro-gram of Fig. 2.5, the declaration in line 9

could have been placed immediately before line 14

Good Programming Practice 2.3Declare only one variable in each declaration and provide a comment that explains thevariable’s purpose in the program.

Portability Tip 2.1C++ allows identifiers of any length, but your C++ implementation may restrict identifierlengths. Use identifiers of 31 characters or fewer to ensure portability.

Good Programming Practice 2.4Choosing meaningful identifiers makes a program self-documenting—a person can un-derstand the program simply by reading it rather than having to refer to program com-ments or documentation.

Good Programming Practice 2.5Avoid using abbreviations in identifiers. This improves program readability.

Good Programming Practice 2.6Do not use identifiers that begin with underscores and double underscores, because C++compilers may use names like that for their own purposes internally. This will prevent thenames you choose from being confused with names the compilers choose.

int number1 = 0; // first integer to add (initialized to 0)

std::cin >> number1; // read first integer from user into number1

2.4 Another C++ Program: Adding Integers 27

Obtaining the First Value from the UserLine 13

displays Enter first integer: followed by a space. This message is called a prompt be-cause it directs the user to take a specific action. We like to pronounce the preceding state-ment as “std::cout gets the string "Enter first integer: ".” Line 14

uses the standard input stream object cin (of namespace std) and the stream extractionoperator, >>, to obtain a value from the keyboard. Using the stream extraction operatorwith std::cin takes character input from the standard input stream, which is usually thekeyboard. We like to pronounce the preceding statement as, “std::cin gives a value tonumber1” or simply “std::cin gives number1.”

When the computer executes the preceding statement, it waits for the user to enter avalue for variable number1. The user responds by typing an integer (as characters), thenpressing the Enter key (sometimes called the Return key) to send the characters to the com-puter. The computer converts the character representation of the number to an integerand assigns (i.e., copies) this number (or value) to the variable number1. Any subsequentreferences to number1 in this program will use this same value.

The std::cout and std::cin stream objects facilitate interaction between the userand the computer.

Users can, of course, enter invalid data from the keyboard. For example, when yourprogram is expecting the user to enter an integer, the user could enter alphabetic charac-ters, special symbols (like # or @) or a number with a decimal point (like 73.5), amongothers. In these early programs, we assume that the user enters valid data. As you progressthrough the book, you’ll learn various techniques for dealing with the broad range of pos-sible data-entry problems.

Obtaining the Second Value from the UserLine 16

prints Enter second integer: on the screen, prompting the user to take action. Line 17

obtains a value for variable number2 from the user.

Calculating the Sum of the Values Input by the UserThe assignment statement in line 19

adds the values of variables number1 and number2 and assigns the result to variable sum us-ing the assignment operator =. We like to read this statement as, “sum gets the value ofnumber1 + number2.” Most calculations are performed in assignment statements. The = op-erator and the + operator are binary operators—each has two operands. In the case of the+ operator, the two operands are number1 and number2. In the case of the preceding = op-erator, the two operands are sum and the value of the expression number1 + number2.

std::cout << "Enter first integer: "; // prompt user for data

std::cin >> number1; // read first integer from user into number1

std::cout << "Enter second integer: "; // prompt user for data

std::cin >> number2; // read second integer from user into number2

sum = number1 + number2; // add the numbers; store result in sum

28 Chapter 2 Introduction to C++ Programming, Input/Output and Operators

Displaying the ResultLine 21

displays the character string Sum is followed by the numerical value of variable sum fol-lowed by std::endl—a stream manipulator. The name endl is an abbreviation for “endline” and belongs to namespace std. The std::endl stream manipulator outputs a new-line, then “flushes the output buffer.” This simply means that, on some systems where out-puts accumulate in the machine until there are enough to “make it worthwhile” to displaythem on the screen, std::endl forces any accumulated outputs to be displayed at that mo-ment. This can be important when the outputs are prompting the user for an action, suchas entering data.

The preceding statement outputs multiple values of different types. The stream inser-tion operator “knows” how to output each type of data. Using multiple stream insertionoperators (<<) in a single statement is referred to as concatenating, chaining or cascadingstream insertion operations.

Calculations can also be performed in output statements. We could have combinedthe statements in lines 19 and 21 into the statement

thus eliminating the need for the variable sum.A powerful feature of C++ is that you can create your own data types called classes (we

introduce this capability in Chapter 3 and explore it in depth in Chapter 9). You can then“teach” C++ how to input and output values of these new data types using the >> and <<operators (this is called operator overloading—a topic we explore in Chapter 10).

2.5 ArithmeticMost programs perform arithmetic calculations. Figure 2.6 summarizes the C++ arithmeticoperators. The asterisk (*) indicates multiplication and the percent sign (%) is the modulusoperator that will be discussed shortly. The arithmetic operators in Fig. 2.6 are all binary op-erators, i.e., operators that take two operands. For example, the expression number1 +

number2 contains the binary operator + and the two operands number1 and number2.Integer division (i.e., where both the numerator and the denominator are integers)

yields an integer quotient; for example, the expression 7 / 4 evaluates to 1 and the expression17 / 5 evaluates to 3. Any fractional part in integer division is truncated —no rounding occurs.

C++ provides the modulus operator, %, that yields the remainder after integer division.The modulus operator can be used only with integer operands. The expression x % y yieldsthe remainder after x is divided by y. Thus, 7 % 4 yields 3 and 17 % 5 yields 2. In later chap-ters, we discuss many interesting applications of the modulus operator, such as determiningwhether one number is a multiple of another (a special case of this is determining whethera number is odd or even).

Good Programming Practice 2.7Place spaces on either side of a binary operator. This makes the operator stand out andmakes the program more readable.

std::cout << "Sum is " << sum << std::endl; // display sum; endline

std::cout << "Sum is " << number1 + number2 << std::endl;

2.5 Arithmetic 29

Arithmetic Expressions in Straight-Line FormArithmetic expressions in C++ must be entered into the computer in straight-line form.Thus, expressions such as “a divided by b” must be written as a / b, so that all constants,variables and operators appear in a straight line. The algebraic notation

is generally not acceptable to compilers, although some special-purpose software packagesdo support more natural notation for complex mathematical expressions.

Parentheses for Grouping SubexpressionsParentheses are used in C++ expressions in the same manner as in algebraic expressions.For example, to multiply a times the quantity b + c we write a * ( b + c ).

Rules of Operator PrecedenceC++ applies the operators in arithmetic expressions in a precise order determined by thefollowing rules of operator precedence, which are generally the same as those in algebra:

1. Operators in expressions contained within pairs of parentheses are evaluated first.Parentheses are at the highest level of precedence. In cases of nested, or embed-ded, parentheses, such as

the operators in the innermost pair of parentheses are applied first.

2. Multiplication, division and modulus operations are applied next. If an ex-pression contains several multiplication, division and modulus operations, oper-ators are applied from left to right. Multiplication, division and modulus are onthe same level of precedence.

3. Addition and subtraction operations are applied last. If an expression containsseveral addition and subtraction operations, operators are applied from left toright. Addition and subtraction also have the same level of precedence.

The rules of operator precedence define the order in which C++ applies operators.When we say that certain operators are applied from left to right, we are referring to theassociativity of the operators. For example, the addition operators (+) in the expression

C++ operationC++ arithmeticoperator

Algebraicexpression

C++expression

Addition + f + 7 f + 7

Subtraction - p – c p - c

Multiplication * bm or b ⋅ m b * m

Division / x / y or or x ÷ y x / y

Modulus % r mod s r % s

Fig. 2.6 | Arithmetic operators.

xy--

ab--

( a * ( b + c ) )

a + b + c

30 Chapter 2 Introduction to C++ Programming, Input/Output and Operators

associate from left to right, so a + b is calculated first, then c is added to that sum to deter-mine the whole expression’s value. We’ll see that some operators associate from right to left.Figure 2.7 summarizes these rules of operator precedence. We expand this table as we in-troduce additional C++ operators. Appendix A contains the complete precedence chart.

Sample Algebraic and C++ ExpressionsNow consider several expressions in light of the rules of operator precedence. Each exam-ple lists an algebraic expression and its C++ equivalent. The following is an example of anarithmetic mean (average) of five terms:

The parentheses are required because division has higher precedence than addition. Theentire quantity ( a + b + c + d + e ) is to be divided by 5.

The following is an example of the equation of a straight line:

No parentheses are required. The multiplication is applied first because multiplication hasa higher precedence than addition.

The following example contains modulus (%), multiplication, division, addition, sub-traction and assignment operations:

The circled numbers indicate the order in which C++ applies the operators. The multiplica-tion, modulus and division are evaluated first in left-to-right order (i.e., they associate from

Operator(s) Operation(s) Order of evaluation (precedence)

( ) Parentheses Evaluated first. If the parentheses are nested, such as in the expres-sion a * ( b + c / d + e ) ), the expression in the innermost pair isevaluated first. [Caution: If you have an expression such as (a + b) *(c - d) in which two sets of parentheses are not nested, but appear“on the same level,” the C++ Standard does not specify the order inwhich these parenthesized subexpressions will be evaluated.]

*

/

%

MultiplicationDivisionModulus

Evaluated second. If there are several, they’re evaluated left to right.

+

-

AdditionSubtraction

Evaluated last. If there are several, they’re evaluated left to right.

Fig. 2.7 | Precedence of arithmetic operators.

Algebra:

C++: m = ( a + b + c + d + e ) / 5;

Algebra:

C++: y = m * x + b;

ma b c d e+ + + +

5-------------------------------------=

y mx b+=

z

6 1 2 4 3 5

= p * r % q + w / x - y;

z = pr%q + w/x – yAlgebra:

C++:

2.5 Arithmetic 31

left to right) because they have higher precedence than addition and subtraction. The additionand subtraction are applied next. These are also applied left to right. The assignment opera-tor is applied last because its precedence is lower than that of any of the arithmetic operators.

Evaluation of a Second-Degree PolynomialTo develop a better understanding of the rules of operator precedence, consider the eval-uation of a second-degree polynomial y = ax 2 + bx + c:

The circled numbers indicate the order in which C++ applies the operators. There is no arith-metic operator for exponentiation in C++, so we’ve represented x2 as x * x. In Chapter 5, we’lldiscuss the standard library function pow (“power”) that performs exponentiation.

Suppose variables a, b, c and x in the preceding second-degree polynomial are initial-ized as follows: a = 2, b = 3, c = 7 and x = 5. Figure 2.8 illustrates the order in which theoperators are applied and the final value of the expression.

Redundant ParenthesesAs in algebra, it’s acceptable to place unnecessary parentheses in an expression to make theexpression clearer. These are called redundant parentheses. For example, the preceding as-signment statement could be parenthesized as follows:

Fig. 2.8 | Order in which a second-degree polynomial is evaluated.

y = ( a * x * x ) + ( b * x ) + c;

6 1 2 4 3 5

y = a * x * x + b * x + c;

(Leftmost multiplication)

(Leftmost multiplication)

(Multiplication before addition)

(Leftmost addition)

(Last addition)

(Last operation—place 72 in y)

Step 1. y = 2 * 5 * 5 + 3 * 5 + 7;

2 * 5 is 10

Step 2. y = 10 * 5 + 3 * 5 + 7;

10 * 5 is 50

Step 3. y = 50 + 3 * 5 + 7;

3 * 5 is 15

Step 4. y = 50 + 15 + 7;

50 + 15 is 65

Step 5. y = 65 + 7;

65 + 7 is 72

Step 6. y = 72

32 Chapter 2 Introduction to C++ Programming, Input/Output and Operators

2.6 Decision Making: Equality and Relational OperatorsWe now introduce a simple version of C++’s if statement that allows a program to takealternative action based on whether a condition is true or false. If the condition is true, thestatement in the body of the if statement is executed. If the condition is false, the bodystatement is not executed. We’ll see an example shortly.

Conditions in if statements can be formed by using the relational operators andequality operators summarized in Fig. 2.9. The relational operators all have the same levelof precedence and associate left to right. The equality operators both have the same level ofprecedence, which is lower than that of the relational operators, and associate left to right.

Using the if StatementThe following example (Fig. 2.10) uses six if statements to compare two numbers inputby the user. If the condition in any of these if statements is satisfied, the output statementassociated with that if statement is executed.

Algebraic relationalor equality operator

C++ relational orequality operator

SampleC++condition Meaning of C++ condition

Relational operators

> > x > y x is greater than y

< < x < y x is less than y

≥ >= x >= y x is greater than or equal to y

≤ <= x <= y x is less than or equal to y

Equality operators

= == x == y x is equal to y

≠ != x != y x is not equal to y

Fig. 2.9 | Relational and equality operators.

Common Programming Error 2.2Reversing the order of the pair of symbols in the operators !=, >= and <= (by writing themas =!, => and =<, respectively) is normally a syntax error. In some cases, writing != as =!will not be a syntax error, but almost certainly will be a logic error that has an effect atexecution time. You’ll understand why when you learn about logical operators inChapter 5. A fatal logic error causes a program to fail and terminate prematurely. Anonfatal logic error allows a program to continue executing, but usually produces incor-rect results.

Common Programming Error 2.3Confusing the equality operator == with the assignment operator = results in logic errors.We like to read the equality operator as “is equal to” or “double equals,” and the assign-ment operator as “gets” or “gets the value of” or “is assigned the value of.” As you’ll see inSection 5.9, confusing these operators may not necessarily cause an easy-to-recognize syn-tax error, but may cause subtle logic errors.

2.6 Decision Making: Equality and Relational Operators 33

1 // Fig. 2.13: fig02_13.cpp2 // Comparing integers using if statements, relational operators3 // and equality operators.4 #include <iostream> // allows program to perform input and output56789

10 // function main begins program execution11 int main()12 {13 int number1 = 0; // first integer to compare (initialized to 0)14 int number2 = 0; // second integer to compare (initialized to 0)1516 cout << "Enter two integers to compare: "; // prompt user for data171819202122 if ( )23 cout << number1 << " != " << number2 << endl;2425 if ( )26 cout << number1 << " < " << number2 << endl;2728 if ( )29 cout << number1 << " > " << number2 << endl;3031 if ( )32 cout << number1 << " <= " << number2 << endl;3334 if ( )35 cout << number1 << " >= " << number2 << endl;36 } // end function main

Enter two integers to compare: 3 73 != 73 < 73 <= 7

Enter two integers to compare: 22 1222 != 1222 > 1222 >= 12

Enter two integers to compare: 7 77 == 77 <= 77 >= 7

Fig. 2.10 | Comparing integers using if statements, relational operators and equality operators.

using std::cout; // program uses coutusing std::cin; // program uses cinusing std::endl; // program uses endl

cin >> number1 >> number2; // read two integers from user

if ( number1 == number2 )cout << number1 << " == " << number2 << endl;

number1 != number2

number1 < number2

number1 > number2

number1 <= number2

number1 >= number2

34 Chapter 2 Introduction to C++ Programming, Input/Output and Operators

using DeclarationsLines 6–8

are using declarations that eliminate the need to repeat the std:: prefix as we did in ear-lier programs. We can now write cout instead of std::cout, cin instead of std::cin andendl instead of std::endl, respectively, in the remainder of the program.

In place of lines 6–8, many programmers prefer to provide the using directive

which enables a program to use all the names in any standard C++ header (such as<iostream>) that a program might include. From this point forward in the book, we’ll usethe preceding directive in our programs. In Chapter 21, Other Topics, we’ll discuss someissues with using directives in large-scale systems.

Variable Declarations and Reading the Inputs from the UserLines 13–14

declare the variables used in the program and initializes them to 0.The program uses cascaded stream extraction operations (line 17) to input two inte-

gers. Remember that we’re allowed to write cin (instead of std::cin) because of line 7.First a value is read into variable number1, then a value is read into variable number2.

Comparing NumbersThe if statement in lines 19–20

compares the values of variables number1 and number2 to test for equality. If the values areequal, the statement in line 20 displays a line of text indicating that the numbers are equal.If the conditions are true in one or more of the if statements starting in lines 22, 25, 28,31 and 34, the corresponding body statement displays an appropriate line of text.

Each if statement in Fig. 2.10 has a single statement in its body and each body state-ment is indented. In Chapter 4 we show how to specify if statements with multiple-state-ment bodies (by enclosing the body statements in a pair of braces, { }, creating what’scalled a compound statement or a block).

using std::cout; // program uses coutusing std::cin; // program uses cinusing std::endl; // program uses endl

using namespace std;

int number1 = 0; // first integer to compare (initialized to 0)int number2 = 0; // second integer to compare (initialized to 0)

if ( number1 == number2 )cout << number1 << " == " << number2 << endl;

Common Programming Error 2.4Placing a semicolon immediately after the right parenthesis after the condition in an if

statement is often a logic error (although not a syntax error). The semicolon causes the bodyof the if statement to be empty, so the if statement performs no action, regardless ofwhether or not its condition is true. Worse yet, the original body statement of the if state-ment now becomes a statement in sequence with the if statement and always executes,often causing the program to produce incorrect results.

2.7 Wrap-Up 35

White SpaceRecall that whitespace characters, such as tabs, newlines and spaces, are normally ignoredby the compiler. So, statements may be split over several lines and may be spaced accordingto your preferences. It’s a syntax error to split identifiers, strings (such as "hello") andconstants (such as the number 1000) over several lines.

Operator PrecedenceFigure 2.11 shows the precedence and associativity of the operators introduced in thischapter. The operators are shown top to bottom in decreasing order of precedence. Allthese operators, with the exception of the assignment operator =, associate from left toright. Addition is left-associative, so an expression like x + y + z is evaluated as if it hadbeen written (x + y) + z. The assignment operator = associates from right to left, so an ex-pression such as x = y = 0 is evaluated as if it had been written x = (y = 0), which, as we’llsoon see, first assigns 0 to y, then assigns the result of that assignment—0—to x.

2.7 Wrap-UpYou learned many important basic features of C++ in this chapter, including displayingdata on the screen, inputting data from the keyboard and declaring variables of fundamen-

Good Programming Practice 2.8A lengthy statement may be spread over several lines. If a single statement must be splitacross lines, choose meaningful breaking points, such as after a comma in a comma-sepa-rated list, or after an operator in a lengthy expression. If a statement is split across two ormore lines, indent all subsequent lines and left-align the group of indented lines.

Operators Associativity Type

() [See caution in Fig. 2.7] grouping parentheses* / % left to right multiplicative+ - left to right additive<< >> left to right stream insertion/extraction< <= > >= left to right relational== != left to right equality= right to left assignment

Fig. 2.11 | Precedence and associativity of the operators discussed so far.

Good Programming Practice 2.9Refer to the operator precedence and associativity chart (Appendix A) when writing ex-pressions containing many operators. Confirm that the operators in the expression are per-formed in the order you expect. If you’re uncertain about the order of evaluation in acomplex expression, break the expression into smaller statements or use parentheses to forcethe order of evaluation, exactly as you’d do in an algebraic expression. Be sure to observethat some operators such as assignment (=) associate right to left rather than left to right.

36 Chapter 2 Introduction to C++ Programming, Input/Output and Operators

tal types. In particular, you learned to use the output stream object cout and the inputstream object cin to build simple interactive programs. We explained how variables arestored in and retrieved from memory. You also learned how to use arithmetic operators toperform calculations. We discussed the order in which C++ applies operators (i.e., therules of operator precedence), as well as the associativity of the operators. You also learnedhow C++’s if statement allows a program to make decisions. Finally, we introduced theequality and relational operators, which you use to form conditions in if statements.

The non-object-oriented applications presented here introduced you to basic pro-gramming concepts. As you’ll see in Chapter 3, C++ applications typically contain just afew lines of code in function main—these statements normally create the objects that per-form the work of the application, then the objects “take over from there.” In Chapter 3,you’ll learn how to implement your own classes and use objects of those classes in appli-cations.

This page intentionally left blank

Symbols-- postfix decrement operator 96-- prefix decrement operator 96^ (bitwise exclusive OR operator) 621,

669^= (bitwise exclusive OR assignment op-

erator) 515, 629, 669, (comma operator) 104:: (binary scope resolution operator) 298:: (scope resolution operator) 60:: (unary scope resolution operator) 668,

672:: unary scope resolution operator 169! (logical NOT operator) 123, 124, 668

truth table 125!= (inequality operator) 32, 668?: (ternary conditional operator) 75, 181.* (pointer-to-member operator) 670,

672.* and ->* operators 670'\0', null character 253'\n', newline character 252[] (operator for map) 507* (multiplication operator) 29* (pointer dereference or indirection op-

erator) 232, 232*= (multiplication assignment operator)

96/ (division operator) 29/* */ (C-style multiline comment) 21// (single-line comment) 20/= (division assignment operator) 96\' (single-quote-character) escape se-

quence 23\" (double-quote-character) escape se-

quence 23\\ (backslash-character) escape sequence

23\a (alert) escape sequence 23\n (newline) escape sequence 23\r (carriage-return) escape sequence 23\t (tab) escape sequence 23& (address operator) 669& (bitwise AND) 621& in a parameter list 166& to declare reference 165&, address operator 231, 232&& (logical AND operator) 123, 181, 668

truth table 123&= (bitwise AND assignment operator)

515, 629, 669# preprocessor operator 791, 796## preprocessor operator 796#pragma preprocessing directive 796#undef preprocessing directive 794% (modulus operator) 29

%= (modulus assignment operator) 96+ (addition operator) 27, 29++ (postfix increment operator) 96

on an iterator 480++ (prefix increment operator) 96

on an iterator 480+= (addition assignment operator) 95

string concatenation 595< (less-than operator) 32<< (left-shift operator) 621<< (stream insertion operator) 22, 28<<= (left-shift assignment operator) 629<= (less-than-or-equal-to operator) 32<algorithm> header 558<algorithm> header 558<forward_list> header 494<unordered_map> header 505, 507<unordered_set> header 501, 504= 27, 35, 279, 308, 480= (assignment operator) 27, 29, 125-= (subtraction assignment operator) 96== (equality operator) 32, 125> (greater-than operator) 32-> (member selection via pointer) 672->* (pointer-to-member operator) 670>= (greater-than-or-equal-to operator) 32>> (right shift operator) 621>>= (right shift with sign extension as-

signment operator) 629| (bitwise inclusive OR operator) 621,

669|= (bitwise inclusive OR assignment op-

erator) 515, 629, 669|| (logical OR operator) 123, 124, 668

truth table 124|| logical OR operator 181~ (bitwise complement operator) 621,

669

Numerics0X 4320x 4322-D array 211

Aabbreviating assignment expressions 95abort 797abort function 272, 574absolute value 131abstract base class 390, 391, 738abstract class 390, 391, 392, 407abstract operation in the UML 734access a global variable 169access function 265

access non-static class data membersand member functions 301

access private member of a class 47access privileges 241, 243access specifier 39, 47, 291, 726

private 47protected 258public 47

access the caller’s data 164access violation 476accessor 49Account class (ATM case study) 690,

693, 697, 699, 700, 708, 715, 716,718, 720, 732, 772

accounts-receivable system 446accumulate algorithm 529, 532, 553,

555, 559accumulated outputs 28action 74, 75action expression 71action expression in the UML 705action of an object 704action state 71action state in the UML 705action state symbol 71activation in a UML sequence diagram

720activation record 159activity diagram 70, 71, 78, 105

do…while statement 111for statement 106if statement 74if…else statement 75in the UML 690, 704, 706, 723sequence statement 71switch statement 120while statement 79

activity in the UML 690, 703, 707activity of a portion of a software system

71actor in use case in the UML 689adapter 509add a new account to a file 472add an integer to a pointer 247addition 29addition assignment operator (+=) 95addition program that displays the sum of

two numbers 24address of a bit field 633address operator (&) 231, 232, 234, 308,

672addressable storage unit 633adjacent_difference algorithm 559adjacent_find algorithm 558aggregation 264, 696aiming a derived-class pointer at a base-

class object 381

Index

800 Index

airline reservation system 456alert escape sequence ('\a') 23, 637algebraic expression 29<algorithm> header 141, 492algorithms 476, 485

accumulate 529, 532all_of 533, 536any_of 533, 536binary_search 209, 533, 536copy_backward 539copy_n 541count 529, 532count_if 529, 532equal 523equal_range 546, 548fill 520, 521fill_n 520, 521find 533, 535find_if 533, 536find_if_not 533, 537for_each 529, 533generate 520, 521generate_n 520, 521includes 544inplace_merge 541, 542is_heap 551is_heap_until 551iter_swap 537, 538lexicographical_compare 524lower_bound 548make_heap 550max 552max_element 529, 532merge 538, 540min 552min_element 529, 532minmax 552minmax_element 529, 532, 553mismatch 522, 524move 540move_backward 540none_of 533, 536pop_heap 551push_heap 551random_shuffle 529, 531remove 524, 526remove_copy 526remove_copy_if 524, 527, 541remove_if 524, 526replace 529replace_copy 527, 529replace_copy_if 527, 529replace_if 527, 529reverse 538, 541reverse_copy 541, 542separated from container 519set_difference 543, 545set_intersection 543, 545set_symmetric_difference

543, 545set_union 543, 546sort 209, 533, 536sort_heap 550swap 537, 538swap_ranges 537, 538transform 529, 533unique 538, 540unique_copy 541, 542upper_bound 548

alias 166, 167, 609for the name of an object 276

alignment 617all 514all_of algorithm 533, 536, 558allocate 321allocate dynamic memory 575allocate memory 140, 321allocator 493allocator_type 479alphabetizing strings 643alter the flow of control 121ambiguity problem 672, 677American National Standards Institute

(ANSI) 2American Standard Code for Information

Interchange (ASCII) 116analysis stage of the software life cycle 688analyzing a project’s requirements 683and operator keyword 668and_eq operator keyword 669“ANDed” 623Android 16

operating system 16smartphone 16

angle brackets (< and >) 173, 791angle brackets (< and >) in templates 583anonymous function objects 518ANSI (American National Standards In-

stitute) 2ANSI/ISO 9899: 1990 2any 514any_of algorithm 533, 536, 558Apache Software Foundation 15append 595append data to a file 447, 448Apple Inc. 16Apple Macintosh 16argument coercion 138argument for a macro 792argument to a function 41arguments in correct order 136arguments passed to member-object con-

structors 283arithmetic assignment operators 95, 96arithmetic calculations 28arithmetic mean 30arithmetic operator 28arithmetic overflow 84, 570arithmetic overflow error 579arithmetic underflow error 579“arity” of an operator 309<array> header 140array

built-in 229, 238name 250notation for accessing elements 251subscripting 251

array 187bounds checking 198

Array class 324Array class definition with overloaded

operators 328Array class member-function and

friend function definitions 329array class template 186Array class test program 324array subscript operator ([]) 328arrow 71

arrow member selection operator (->)265

arrow operator (->) 293arrowhead in a UML sequence diagram

720ASCII (American Standard Code for In-

formation Interchange)Character Set 116, 252, 422

assert 797assign member function of class

string 593assign member function of list 498assign one iterator to another 484assigning addresses of base-class and de-

rived-class objects to base-class and de-rived-class pointers 378

assigning class objects 279assignment operator functions 333assignment operators 27, 35, 95, 279,

308, 480*= multiplication assignment opera-

tor 96/= division assignment operator 96%= modulus assignment operator 96+= addition assignment operator 95-= subtraction assignment operator

96assignment statement 27, 97associate from left to right 35, 98associate from right to left 35, 98, 116association 508association (in the UML) 694, 695, 696,

728, 729name 695

associative container 480, 483, 500, 503ordered 476, 500unordered 476, 500

associative container functionscount 503equal_range 503find 503insert 503, 507lower_bound 503upper_bound 503

associativity 124, 126associativity chart 35associativity not changed by overloading

309associativity of operators 29, 35asterisk (*) 28asynchronous call 717asynchronous event 570at member function 493, 514

class string 308, 595class vector 226

ATM (automated teller machine) casestudy 683, 688

ATM class (ATM case study) 693, 694,695, 699, 702, 703, 708, 714, 715,716, 717, 718, 727

ATM system 689, 690, 691, 692, 693,698, 703, 707, 726

atof 647atoi 647atol 648attribute 45, 728, 729

compartment in a class diagram 701declaration in the UML 701, 703

Index 801

attribute (cont.)in the UML 5, 41, 693, 698, 700,

701, 703, 707, 736name in the UML 701of a class 4of an object 5

attributes of a variable 152auto keyword 213auto_ptr object manages dynamically

allocated memory 577automated teller machine 456automated teller machine (ATM) 683,

684, 688user interface 684

automatic array 188automatic array initialization 199automatic local array 199automatic local variable 153, 156, 167automatic object 571automatic storage class 152, 200automatic storage duration 153automatically destroyed 156average 30average calculation 79, 85avoid naming conflicts 291avoid repeating code 270

Bback member function of queue 511back member function of sequence con-

tainers 492back_inserter function template 540,

542backslash (\) 22, 794backslash escape sequence (\\) 23backward traversal 607bad member function 442bad_alloc exception 493, 572, 574,

578bad_cast exception 578bad_typeid exception 578badbit 449badbit of stream 422, 442BalanceInquiry class (ATM case

study) 693, 696, 699, 700, 702, 704,708, 715, 716, 717, 718, 727, 733,734, 735

Bank account program 466BankDatabase class (ATM case study)

693, 697, 699, 708, 715, 716, 717,718, 720, 727, 729

banking system 456bar chart 193, 194bar chart printing program 194bar of asterisks 193, 194base 2 621base case(s) 175, 179, 182base class 343, 345, 733base-class catch 578base-class constructor 370base-class exception 578base-class member accessibility in derived

class 371base-class pointer to a derived-class object

389base-class private member 361base-class subobject 678base e 132

base specified for a stream 436base-10 number system 132, 432base-16 number system 432base-8 number system 432base-class initializer syntax 359base-class member function redefined in a

derived class 368BasePlusCommissionEmployee class

header 402BasePlusCommissionEmployee class

implementation file 402BasePlusCommissionEmployee class

represents an employee who receives abase salary in addition to a commis-sion 352

BasePlusCommissionEmployee classtest program 355

BasePlusCommissionEmployee classthat inherits from class Commission-Employee, which does not provideprotected data 367

basic searching and sorting algorithms ofthe Standard Library 533

basic_fstream class template 420, 446basic_ifstream class template 420,

445basic_ios class template 418, 677basic_iostream class template 418,

420, 446, 677basic_istream class template 418,

446, 677basic_istringstream class template

609basic_ofstream class template 446basic_ostream class template 420,

446, 677basic_ostringstream class template

609basic_string class template 592begin function 240begin iterator 608beginmember function of class string

608begin member function of containers

479begin member function of first-class

containers 480beginning of a file 452beginning of a stream 452behavior 707

of a class 4behavior of the system 703, 704, 707, 716bell 23Bell Laboratories 2bidirectional iterator 482, 483, 494, 501,

504, 505, 518, 540, 541, 542bidirectional iterator operations 484bidirectional navigability in the UML

727binary (base 2) number system 781binary arithmetic operator 90binary function 553binary function object 553binary number 634binary number system 650binary operator 27, 28binary predicate function 497, 523, 532,

536, 540, 545, 550

binary_search algorithm 209, 533,536, 558

bit 616bit field 621, 630, 633bit-field manipulation 633bit-field member of structure 631bit fields save space 633bit manipulation 621bitand operator keyword 669bitor operator keyword 669“bits-and-bytes” level 621bitset 477, 513, 514, 515<bitset> header 140bitwise AND assignment 669bitwise AND assignment operator (&=)

629bitwise AND operator (&) 621, 621, 624,

626bitwise AND, bitwise inclusive-OR, bit-

wise exclusive-OR and bitwise com-plement operators 624

bitwise assignment operator keywords669

bitwise assignment operators 515, 629bitwise complement 622, 669bitwise complement operator (~) 621,

624, 627, 629, 788bitwise exclusive OR 669bitwise exclusive OR assignment operator

(^=) 629bitwise exclusive OR operator (^) 621,

624, 627bitwise inclusive OR 669bitwise inclusive OR assignment operator

(|=) 629bitwise inclusive OR operator (|) 461,

621, 624, 626bitwise left-shift operator (<<) 304, 627bitwise logical OR 515bitwise operator keywords 669bitwise operators 621, 622, 629bitwise right-shift operator (>>) 304bitwise shift operator 627BlackBerry OS 15block 34, 44, 66, 77, 89, 153, 155, 156block is active 153block is exited 153block of data 655block of memory 498, 655block scope 155, 265

variable 265body of a class definition 39body of a function 21, 22, 40body of a loop 102, 105Booch, Grady 684bool data type 74bool value false 74bool value true 74boolalpha stream manipulator 125,

432, 438Boolean attribute in the UML 699Boost C++ Libraries 17boundary of a storage unit 633bounds checking 198braces ({}) 22, 34, 66, 77, 89, 117braces in a do…while statement 112bracket ([]) 187break statement 118, 121

802 Index

break statement exiting a for statement121

brittle software 364buffer is filled 420buffer is flushed 420buffer overflow 198buffered output 420buffered standard error stream 418buffering 443building-block approach 3built-in array 229, 238business-critical computing 565byte 621

C.C extension 6C legacy code 791, 792, 797C-like pointer-based array 477C string 252c_str member function of class string

607C++ 2C++ compiler 7C++ development environment 7, 8C++ preprocessor 7, 21C++ Standard Library 3

<string> file 43class template vector 221header location 57headers 139string class 43

C++11 17, 178all_of algorithm 536anonymous function objects 518any_of algorithm 536associative container keys are immu-

table 477auto keyword 213, 503begin function 240, 489cbegin container member function

489cend container member function

489compiler fix for types ending in >>

502copy_n algorithm 541crbegin container member func-

tion 490crend container member function

490default type arguments for function

template type parameters 589delegating constructor 271end function 240, 489find_if_not algorithm 537forward_list class template 476,

494in-class initializer 120, 260insert container member function

(now returns an iterator) 493,494

iota algorithm 559is_heap algorithm 551is_heap_until algorithm 551list initialization 94, 507list initialization of a return type 507list initialization of associative con-

tainer 507

C++11 (cont.)list initializer 271list initializers 490minmax algorithm 552minmax_element algorithm 532,

553move algorithm 540move assignment operator 478move constructor 478move_backward algorithm 540noexcept 571none_of algorithm 536non-member container swap func-

tion 478nullptr constant 230override 384random-number generation 195scoped enum 150shrink_to_fit container member

function for vector and deque490

specifying an enum’s integral type150

stod function 612stof function 612stoi function 612stol function 612stold function 612stoll function 612stoul function 612stoull function 612to_string function 612trailing return types for functions

175unique_ptr class template 575,

575, 578unordered_multimap class tem-

plate 477unordered_multiset class tem-

plate 477unordered_set class template 477

calculations 28, 70call a function 41call stack 242calling function (caller) 40, 47calling functions by reference 233camel case 39capacity member function

of string 601of vector 488

capacity of a string 599Card Shuffling and Dealing

simulation 616, 618, 620carriage return ('\r') escape sequence

23, 634, 637carry bit 788cascading member function calls 293,

294, 296cascading stream insertion operations 28case label 117, 118case sensitive 26CashDispenser class (ATM case study)

693, 695, 699, 700, 708, 720casino 146<cassert> header 141, 797cast 249

downcast 383cast away const-ness 662cast expression 794

cast operator 85, 90, 139, 337, 338cast operator function 337cast variable visible in debugger 792catch a base class object 578catch all exceptions 579catch block 226catch clause (or handler) 566, 570catch handler 564catch related errors 572catch(...) 579cbegin member function of containers

479cbeginmember function of vector 489<cctype> header 140, 634CD 445ceil function 131cend member function of containers 479cend member function of vector 489cerr (standard error stream) 9, 66, 418,

419, 445<cfloat> header 141chaining stream insertion operations 28char ** 648char data type 26, 116, 139, 606, 621char16_t 418char32_t 418character 616character array 253, 606character constant 252character-handling functions 634

isdigit, isalpha, isalnum andisxdigit 635

islower, isupper, tolower andtoupper 636

isspace, iscntrl, ispunct, is-print and isgraph 637

character presentation 141character sequences 456character set 120character string 22, 188character’s numerical representation 116characters represented as numeric codes

644character-string manipulation 633checked access 595cin (standard input stream) 9, 27, 418,

419, 445, 449function getline 254

cin.clear 442cin.eof 422, 442cin.get function 115, 116, 423cin.tie function 443circular include 730class 4, 701, 707, 711, 726, 792

attribute 45client-code programmer 62constructor 50data member 5, 45default constructor 51, 53define a constructor 52define a member function 38implementation programmer 62instance of 46interface 58interface described by function pro-

totypes 58member function 38member-function implementations

in a separate source-code file 59

Index 803

class (cont.)name 728naming convention 39object of 46public services 58services 49

class average on a quiz 79class average problem 79class definition 39class development 324class diagram

for the ATM system model 697, 722in the UML 690, 693, 696, 698,

701, 708, 726, 729, 735, 736,737

class diagram (UML) 41class hierarchy 344, 389, 391class-implementation programmer 62class keyword 173, 583class libraries 109class library 372class members default to private access

616class scope 155, 261, 264class-scope variable is hidden 265class template 186, 582, 592

auto_ptr 575definition 582scope 585specialization 582Stack 583, 585

class variable 207Classes 3

Array 324bitset 477, 513, 514, 515deque 485, 498exception 562forward_list 485, 494invalid_argument 578list 485, 494multimap 505out_of_range exception class 226priority_queue 512queue 511, 511runtime_error 562, 570set 504stack 509string 43unique_ptr 575vector 221

classic stream libraries 417clear function of ios_base 442clear member function of containers

479clear member function of first-class

containers 494client code 376client-code programmer 62client of a class 707, 717client of an object 48<climits> header 141clog (standard error buffered) 418, 419,

445close member function of ofstream

450<cmath> header 109, 140code 5CodeLite 7coin tossing 141

collaboration 714, 715, 717collaboration diagram in the UML 691,

716collaboration in the UML 714colon (:) 155, 286, 675column 211column headings 189column subscript 211comma operator (,) 104, 181comma-separated list

of parameters 13625, 35, 104, 230command-line argument 240comma-separated list of base classes 675comment 20CommissionEmployee class header 399CommissionEmployee class implemen-

tation file 400CommissionEmployee class represents

an employee paid a percentage of grosssales 347

CommissionEmployee class test pro-gram 350

CommissionEmployee class uses mem-ber functions to manipulate its pri-vate data 365

Common Programming Errors overviewxxiii

communication diagram in the UML691, 716, 717

commutative 336commutative operation 336comparator function object 501, 505comparator function object less 501,

512compare iterators 484compare member function of class

string 597comparing

strings 639, 642comparing blocks of memory 655comparing strings 595compilation error 95compilation unit 667compile 7compiler 21, 90compiling

multiple-source-file program 63compl operator keyword 669complement operator (~) 621complex conditions 123component 3composition 264, 283, 287, 343, 346,

695, 696, 721compound interest 108

calculation with for 108compound statement 34computing the sum of the elements of an

array 193concatenate 595

stream insertion operations 28strings 641

concrete class 390concrete derived class 395condition 32, 73, 75, 111, 122conditional compilation 791, 794conditional execution of preprocessing di-

rectives 791conditional expression 75

conditional operator (?:) 75conditional preprocessing directives 794conditionally compiled output statement

795confusing equality (==) and assignment

(=) operators 32, 127conserving memory 153consistent state 65const 281, 313, 792const keyword 163const member function 40, 281const member function on a const ob-

ject 282constmember function on a non-const

object 282const object 192, 282const object must be initialized 192const objects and const member func-

tions 282const qualifier 191, 240, 661const qualifier before type specifier in

parameter declaration 166const variables must be initialized 192const version of operator[] 335const with function parameters 240const_cast

cast away const-ness 662const_cast demonstration 662const_cast operator 661, 662, 663const_iterator 479, 480, 481, 483,

484, 503, 505, 608const_pointer 479const_reference 479const_reverse_iterator 479, 480,

484, 490, 608constant integral expression 119constant pointer

to an integer constant 243to constant data 241, 243, 244to nonconstant data 241, 243

constant reference 334constant reference parameter 166constant variable 191“const-ness” 663constructed inside out 288constructor 50

cannot be virtual 389cannot specify a return type 50conversion 337, 339copy 332default 53default arguments 269defining 52explicit 339function prototype 59in a UML class diagram 54inherit 370inherit from base class 370naming 52parameter list 52single argument 339, 340

constructors and destructors called auto-matically 272

container 140, 475, 476container adapter 476, 477, 483, 509

priority_queue 512queue 511stack 509

804 Index

container adapter functionspop 509push 509

container class 265, 328, 476containers

begin function 479cbegin function 479cend function 479clear function 479crbegin function 479crend function 479empty function 478end function 479erase function 479insert function 478max_size function 478rbegin function 479rend function 479size function 478swap function 478

continue statement 121continue statement terminating a single

iteration of a for statement 122control characters 637control statement 70, 73, 74

nesting 73stacking 73

control statements 73do…while 110, 111do…while repetition statement 72for 102, 104for repetition statement 72if 32if single-selection statement 71if…else double-selection state-

ment 72nested if…else 77nesting 92repetition statement 73selection statement 73sequence statement 73switch 112, 119while 102, 110while repetition statement 72

control variable 102control-variable name 104controlling expression 117converge on the base case 182conversion constructor 337, 339conversion operator 337

explicit 340conversions among fundamental types

by cast 337convert a binary number to decimal 786convert a hexadecimal number to decimal

786convert among user-defined types and

built-in types 337convert an octal number to decimal 786convert between types 337convert lowercase letters 140convert strings to floating-point types 612convert strings to integral types 612converting strings to C-style strings and

character arrays 606copy algorithm 492, 558copy assignment 279copy constructor 280, 287, 327, 332,

334, 370, 478, 480

copy member function of class string461, 607

copy of the argument 241copy_backward algorithm 539, 558copy_if algorithm 558copy_n algorithm 541, 558copy-and-paste approach 356copying strings 640correct number of arguments 136correct order of arguments 136correctly initializing and using a constant

variable 191cos function 131cosine 131count algorithm 529, 532, 558count function of associative container

503count_if algorithm 529, 532, 558counter 154counter-controlled repetition 79, 88, 92,

101, 182counter-controlled repetition with the

for statement 103counter variable 82counting loop 102cout (<<) (the standard output stream)

418, 419, 445cout (standard output stream) 9cout (the standard output stream) 21,

24, 27cout.put 421cout.write 426__cplusplus predefined symbolic con-

stant 797.cpp extension 6CPU (central processing unit) 8craps simulation 146, 147, 150crbegin member function of containers

479crbegin member function of vector

490create an object (instance) 40create your own data types 28CreateAndDestroy class

definition 273member-function definitions 274

creating a random access file 457Creating a random-access file with 100

blank records sequentially 461Creating a sequential file 447creating an association 508Credit inquiry program 453credit processing program 458crend member function of containers

479crend member function of vector 490<cstdio> header 141<csdtlib> header 574<cstdlib> header 140, 141, 646<cstring> header 140, 640<ctime> header 140, 146<Ctrl>-d 116, 429, 449Ctrl key 116<Ctrl>-z 116, 429, 449<cstdlib> header 142current position in a stream 452cursor 22.cxx extension 6

Ddangerous pointer manipulation 407dangling-else problem 77dangling pointer 333dangling reference 167data hiding 47, 49data member 5, 45, 46, 726data member function of class string

607data members 38data persistence 445data structures 475data types

bool 74char 116, 139double 85, 108float 85, 138int 25long 120long double 138long int 120, 139long long 120, 138long long int 138short 120short int 120unsigned 145unsigned char 139unsigned int 139, 145unsigned long 138unsigned long int 138unsigned long long 138unsigned long long int 138unsigned short 139unsigned short int 139

data types in the UML 44Date class 283, 316Date class definition 283Date class definition with overloaded in-

crement operators 316Date class member function definitions

284Date class member-function and

friend-function definitions 317Date class test program 319__DATE__ predefined symbolic constant

797date source file is compiled 797deallocate 321deallocate memory 321, 575debugger 792debugging 144debugging aid 795debugging tool 797dec stream manipulator 427, 432, 436decimal (base 10) number system 649,

650, 781decimal (base-10) number system 432decimal numbers 436, 634decimal point 85, 90, 91, 109, 421, 432decision 74decision in the UML 705decision symbol 74declaration 25declaration of a function 59declaring a static member function

const 301decrement

a pointer 247decrement a control variable 101

Index 805

decrement operator (--) 96decrement operators 315default access mode for class is private

47default argument 167, 266default arguments with constructors 266default case 117, 118, 144default constructor 51, 53, 267, 288, 316,

327, 332, 370, 478provided by the compiler 53provided by the programmer 53

default copy constructor 287default delimiter 425default memberwise assignment 279default memberwise copy 332default precision 90default to decimal 436default to public access 616default type argument for a type parame-

ter 589default type arguments for function tem-

plate type parameters 589default_random_engine 151#define 794, 796define a constructor 52define a member function of a class 38Define class GradeBook with a member

function displayMessage, create aGradeBook object, and call its dis-playMessage function 38

Define class GradeBook with a memberfunction that takes a parameter, createa GradeBook object and call its dis-playMessage function 42

#define NDEBUG 797#define PI 3.14159 792#define preprocessing directive 792#define preprocessor directive 259defining occurrence 9definition 101Deitel Buzz Online newsletter 18delegating constructor 271delete 333, 575, 577delete [] (dynamic array deallocation)

323delete a record from a file 472delete operator 321, 389deleting dynamically allocated memory

333delimiter 254, 644delimiter (with default value '\n') 423delimiting characters 644Deposit class (ATM case study) 693,

696, 699, 700, 708, 715, 716, 724,727, 733, 734

DepositSlot class (ATM case study)693, 695, 699, 708, 716, 728

<deque> header 140, 499deque class template 485, 498

push_front function 499shrink_to_fit member function

490dereference

a const iterator 482a null pointer 232a pointer 232, 235, 241an iterator 480, 481, 484an iterator positioned outside its con-

tainer 490

dereferencing operator (*) 232derive one class from another 264derived class 343, 345, 372, 733, 734

indirect 401derived-class catch 578descriptive words and phrases 699, 701deserialized object 473design process 5, 683, 689, 708, 713design specification 689destructor 272, 357, 478

called in reverse order of constructors272

destructor in a derived class 370destructors called in reverse order 370Dev C++ 7diagnostics that aid program debugging

141diamond inheritance 677diamond symbol 71, 74dice game 146die rolling

using an array instead of switch195

difference_type 480digit 26, 253, 781direct base class 345directly reference a value 229disk 8, 9disk drive 417disk I/O completion 570disk space 449, 573, 574displacement 410display screen 417, 419divide by zero 9DivideByZeroException 566divides function object 554division 29do…while repetition statement 72, 110,

111dollar amount 109dot (.) operator 40dot operator (.) 265, 293, 384, 576dotted line 71double 26double data type 85, 108, 138double-ended queue 498double-precision floating-point number

89double quote 22, 23double-selection statement 72double-word boundary 617“doubly initializing” member objects 288doubly linked list 494, 477downcasting 383driver program 55dummy value 85duplicate keys 500, 505DVD 445dynamic binding 384, 406, 407, 410dynamic casting 411dynamic data structure 229dynamic memory 575dynamic memory management 321dynamic storage duration 153dynamic_cast 413, 578dynamically allocate array of integers 328dynamically allocated memory 279, 280,

333, 389, 575allocate and deallocate storage 272

dynamically allocated storage 332dynamically determine function to exe-

cute 383

EEclipse 7Eclipse Foundation 15edit 6edit a program 6editor 6element of an array 186elided UML diagram 694#elif 795emacs 6embedded parentheses 29embedded system 15Employee class 283

definition showing composition 285definition with a static data member

to track the number of Employeeobjects in memory 299

header 394implementation file 395member-function definitions 286,

299empty member function

of containers 478of priority_queue 513of queue 511of sequence container 493of stack 509of string 307, 601

empty parentheses 40, 41, 43empty statement 78empty string 48, 601encapsulate 47encapsulation 5, 49, 262, 278, 288end function 240end line 28end member function of class string

608end member function of containers 479end member function of first-class con-

tainer 480end of a sequence 536end of a stream 452“end of data entry” 85end-of-file 116, 117, 254, 442#endif preprocessing directive 795#endif preprocessor directive 259endl 28, 90end-of-file 449end-of-file indicator 449end-of-file key combination 449end-of-file marker 445Enter key 27enter key 117, 118enum

scoped 150specifying underlying integral type

150unscoped 150

enum class 150enum keyword 149enum struct 150enumeration 149, 792enumeration constant 149, 794EOF 116, 422, 425, 634

806 Index

eof member function 422, 442eofbit of stream 442equal algorithm 523, 558equal to 32equal_range algorithm 546, 548, 558equal_range function of associative

container 503equal_to function object 554equality and relational operators 33equality operator (==) 324, 480equality operators 32, 33equality operators (== and !=) 74, 123equation of straight line 30erase 603erase member function of class string

603erase member function of containers

479erase member function of first-class

containers 493e-reader device 16#error preprocessing directive 795error

off-by-one 104error bits 425error detected in a constructor 571error state of a stream 422, 440, 441escape character 22escape early from a loop 121escape sequence 22, 24escape sequences

\' (single-quote character) 23\" (double-quote character) 23\\ (backslash character) 23\a (alert) 23\n (newline) 23\r (carriage return) 23\t (tab) 23, 118

event 703<exception> header 140exception 225, 561

handler 225handling 221parameter 226

exception class 562, 578what virtual function 562

exception classes derived from commonbase class 572

exception handling 140, 561out_of_range exception class 226what member function of an excep-

tion object 226<exception> header 562, 578exception object 566exception parameter 564exceptional condition 118Exceptions 226

bad_alloc 572bad_cast 578bad_typeid 578length_error 578logic_error 578out_of_range 226, 578overflow_error 578underflow_error 579

executable image 8executable program 7execute a program 6, 8execution-time error 9

execution-time overhead 407exit 449exit a function 23exit function 272, 273, 574EXIT_FAILURE 449EXIT_SUCCESS 449exp function 131expand a macro 793explicit constructor 339explicit conversion 90explicit keyword 52, 339

conversion operators 340exponential “explosion” of calls 182exponential complexity 182exponential function 131exponentiation 31, 108expression 74, 75, 90, 104extensibility 376extensibility of C++ 314extensible language 179extensible markup language (XML) 473extensible programming language 40extern keyword 154extern storage-class specifier 152

Ffabs function 131Facebook 15factorial 176, 177, 179fail member function 442failbit 449failbit of stream 422, 426, 442false 32false 74, 75, 182, 438fatal logic error 32fatal runtime error 9fault-tolerant programs 225, 561Fibonacci series 179, 182field width 110, 189, 426, 429fields larger than values being printed 435FIFO 477, 498FIFO (first-in, first-out) 511file 445, 451file of n bytes 445file open mode 447, 450file open modes

ios::app 447ios::ate 448ios::binary 448, 461, 464ios::in 448, 450ios::out 447ios::trunc 448

__FILE__ predefined symbolic constant796

file processing 417, 420file scope 155, 264filename 447, 450filename extensions 6file-position pointer 452, 464, 472file-processing classes 420fill algorithm 520, 521, 558fill character 261, 426, 429, 434, 435fill member function 433, 435fill member function of basic_ios 442fill_n algorithm 520, 521, 558final

class 389member function 389

final state 71final state in the UML 705final value of a control variable 101, 105find algorithm 533, 535, 558find function of associative container

503find member function of class string

601, 603find_end algorithm 558find_first_not_of member function

of class string 603find_first_of algorithm 558find_first_of member function of

class string 603find_if algorithm 533, 536, 558find_if_not algorithm 533, 537, 558find_last_ofmember function of class

string 603finding strings and characters in a string

601first data member of pair 503first-in, first-out (FIFO) data structure

511first-class container 477, 479, 480, 483,

489, 494begin member function 480clear function 494end member function 480erase function 493

first-in, first-out (FIFO) 477, 498fixed notation 421, 432, 437fixed-point format 91fixed-point value 110fixed stream manipulator 91, 432, 433,

437fixed-size data structure 238flag value 85flags member function of ios_base

439flash drive 445float data type 85, 138floating point 432, 437floating-point arithmetic 304floating-point division 90floating-point literal 89

double by default 89floating-point number 85, 90

double data type 85double precision 89float data type 85single precision 89

floating-point size limits 141floating-point number in scientific format

437floor function 131flow of control 78, 88flow of control in the if…else state-

ment 75flow of control of a virtual function call

408flush buffer 443flush output buffer 28flushing stream 426fmod function 131fmtflags data type 439for repetition statement 72, 102, 104for repetition statement examples 105for_each algorithm 529, 533, 558force a decimal point 421

Index 807

forcing a plus sign 434form feed ('\f') 634, 637formal parameter 136formal type parameter 173format error 442format of floating-point numbers in sci-

entific format 437format state 426, 439format-state stream manipulators 432formatted data file processing 445formatted I/O 417formatted input/output 456formatted text 456forward declaration 730forward iterator 482, 518, 521, 529, 536,

538, 540forward iterator operations 484forward iterators 494<forward_list> header 140forward_list class template 476, 485,

494splice_after member function

498fractional parts 90fragile software 364free function (global function) 262free store 321friend function 289, 346friend of a derived class 675friends are not member functions 291Friends can access private members of

class 289friendship granted, not taken 289front member function of queue 511frontmember function of sequence con-

tainers 492front_inserter function template 540<fstream> header 140fstream 446, 462, 466, 471<fstream> header 445function 3, 9, 21, 137

argument 41call 136call overhead 163call stack 159declaration 137definition 136, 156empty parentheses 40, 41, 43header 40local variable 44multiple parameters 44name 154overloading 170parameter 41, 43parameter list 43prototype 58, 136, 137, 156, 165,

235return a result 47signature 137, 171that takes no arguments 162trailing return type 175

function body 40function call 41function call operator () 340, 410function call stack 242function object 501, 505, 518, 553

binary 553divides 554equal_to 554

function object (cont.)greater 554greater_equal 554less 554less_equal 554logical_end 554logical_not 554logical_or 554minus 554modulus 554multiplies 554negate 554not_equal_to 554plus 554predefined in the STL 553

function object less< int > 501function object less< T > 505, 512function overhead 793function overloading 416function pointer 407, 410, 518, 553function prototype 58, 109, 289, 792

parameter names optional 59function prototype scope 155, 156function scope 155, 155function template 173, 582, 589function template specialization 173<functional> header 141, 553functional structure of a program 22functions 3functions for manipulating data in the

standard library containers 141functions with empty parameter lists 162function-template specialization 582fundamental type 26fundamental types

unsigned int 82

Ggame of chance 146game of craps 147game playing 141gcount function of istream 426general class average problem 85general utilities library <cstdlib> 797generalities 376generalization in the UML 733generalized numeric operations 557general-utilities library <cstdlib> 646generate algorithm 520, 521, 558generate_n algorithm 520, 521, 558generating values to be placed into ele-

ments of an array 191generator function 520generic algorithms 519generic programming 582get a value 49get and set functions 48get member function 422, 423get pointer 452getline function for use with class

string 593getline function of cin 424getline function of the string header

43, 48gets the value of 32global 60global function 130global identifier 665

global namespace 667global namespace scope 155, 156, 272,

298global object constructors 272global scope 272, 274, 667global variable 154, 156, 158, 169, 667golden mean 179golden ratio 179good function of ios_base 442Good Programming Practices overview

xxiiigoodbit of stream 442goto elimination 70goto statement 70GradeBook.cpp 80, 86GradeBook.h 80, 85graph information 194Graphical User Interface (GUI) 16greater function object 554greater_equal function object 554greater-than operator 32greater-than-or-equal-to operator 32guard condition 74guard condition in the UML 705GUI (Grahical User Interface) 16guillemets (« and ») in the UML 54

H.h filename extension 54half-word 617handle on an object 264hard disk 445hardcopy printer 9hardware platform 2has-a relationship 343, 695, 283header 54, 62, 139, 259, 372, 791Headers

<algorithm> 492, 558<cmath> 109<deque> 499<exception> 562<forward_list> 494<fstream> 445<functional> 553<iomanip.h> 90<iostream> 21, 116<list> 494<map> 505, 507<memory> 575<numeric> 559<queue> 511, 512<set> 501<stack> 509<stdexcept> 562, 578<string> 43<typeinfo> 413<unordered_map> 505, 507<unordered_set> 501, 504<vector> 221how they are located 57name enclosed in angle brackets (<

>) 57name enclosed in quotes (" ") 57

heap 321, 512, 548, 551heapsort sorting algorithm 548helper function 265hex stream manipulator 427, 432, 436

808 Index

hexadecimal 650integer 232

hexadecimal (base-16) number 421, 427,432, 436, 649, 781

hexadecimal notation 421hexadecimal number system 634hide implementation details 288hide names in outer scopes 155hierarchy of exception classes 578hierarchy of shapes 390“highest” type 138high-level I/O 417horizontal tab ('\t') 23, 634, 637host object 283

IIDE (integrated development environ-

ment) 6identifier 26, 72, 156identifiers for variable names 152IEC (International Electrotechnical

Commission) 2#if 795#if preprocessing directive 795if single-selection statement 71, 74if statement 32, 74if statement activity diagram 74if…elsedouble-selection statement 72,

74, 75if…else statement activity diagram 75#ifdef preprocessing directive 795#ifndef preprocessor directive 259#ifndef preprocessing directive 795ifstream 446, 450, 451, 464ifstream constructor function 450ignore 312ignore function of istream 425implementation inheritance 393implementation of a member function

changes 270implementation phase 737implementation process 708, 726implicit conversion 90, 338, 339

via conversion constructors 339implicit first argument 291implicit handle 264implicit, user-defined conversions 338implicitly virtual 384improper implicit conversion 338in-class initializers 260in-memory formatting 609in-memory I/O 609in-class initializer (C++11) 120#include 791, 791#include "filename" 791include guard 257, 259#include <iomanip> 90#include <iostream> 21#include preprocessing directive 791#include preprocessor directive 137includes algorithm 543, 544, 559including a header multiple times 259increment

a pointer 247increment a control variable 101, 104,

105increment an iterator 484increment operator 315

increment operator (++) 96indentation 73, 76independent software vendor (ISV) 3index 186indexed access 498indirect base class 345indirect derived class 401indirection 229, 407indirection operator (*) 232, 234indirectly reference a value 229inequality 668inequality operator (!=) 324inequality operator keywords 668infinite loop 89, 104, 176information hiding 5inherit constructors 370inherit constructors from base class 370inherit interface 390inherit members of an existing class 343Inheritance

hierarchy for university Communi-tyMembers 344

inheritance 5, 258, 264, 343, 345, 732,733, 736, 737examples 344hierarchy 384implementation vs. interface inheri-

tance 393multiple 672relationships of the I/O-related class-

es 420, 446virtual base class 679

initial state 71initial state in the UML 703, 705initial value of a control variable 101, 103initial value of an attribute 702initialize a pointer 230initializer 189initializer list 189, 253initializer_list 552initializer_list class template 336initializing an array’s elements to zeros

and printing the array 189initializing multidimensional arrays 212initializing the elements of an arraywith

a declaration 190inline 164, 335, 794inline function 163inline function 792, 793inline function to calculate the volume

of a cube 164inline keyword 163inner block 155inner_product algorithm 559innermost pair of parentheses 29inplace_merge algorithm 542, 559input a line of text 424Input and output stream iterators 481input from string in memory 140input iterator 482, 484, 523, 526, 529,

532, 540, 545input line of text into an array 254input/output library functions 141input/output of objects 473input/output operations 71input/output stream header <iostream>

21input sequence 481input stream 422, 423

input stream iterator 481input stream object (cin) 27inputting from strings in memory 609insert function of associative container

503, 507insert member function of class

string 605insert member function of containers

478insert member function of sequence

container 493inserter function template 540insertion at back of vector 486instance 4instance of a class 46instant access processing 466instant-access application 456instruction 8int 21, 26, 138int & 165int operands promoted to double 90integer 21, 25integer arithmetic 304Integer class definition 575integer division 28, 90integer promotion 90integers prefixed with 0 (octal) 436integers prefixed with 0x or 0X (hexadec-

imal) 436integral constant expression 112integral size limits 141integrated development environment

(IDE) 6interaction diagram in the UML 716interactions among objects 714, 717interest rate 108interface 58Interface Builder 16interface inheritance 393interface of a class 58internal spacing 434internal stream manipulator 432, 434International Electrotechnical Commis-

sion (IEC) 2International Standards Organization

(ISO) 2invalid_argument class 578invalid_argument exception 493invalid_argument exception class 260invoking a non-const member function

on a const object 281<iomanip> header 140, 791, 418, 427<iomanip.h> header 90iOS 15ios_base base class 440ios_base class

precision function 427width member function 429

ios::app file open mode 447ios::ate file open mode 448ios::beg seek direction 452ios::binary file open mode 448, 461,

464ios::cur seek direction 452ios::end seek direction 452ios::in file open mode 448, 450ios::out file open mode 447ios::trunc file open mode 448

Index 809

<iostream> header 21, 139, 418, 419,791, 116, 445

iota algorithm 559iPod Touch 16is a 675is-a relationship (inheritance) 343, 372is_heap algorithm 551, 559is_heap_until algorithm 551, 559is_partitioned algorithm 558is_permutation algorithm 558is_sorted algorithm 558is_sorted_until algorithm 558isalnum 634isalpha 634iscntrl 634, 637isdigit 634, 636isgraph 634, 637islower 634, 636ISO 2isprint 634, 637ispunct 634, 637isspace 634, 637istream 420istream class 452, 457, 464, 471, 473,

609peek function 425seekg function 452tellg function 452

istream member function ignore 312istream_iterator 481istringstream 611istringstream class 609, 611isupper 634, 636isxdigit 634, 634iter_swap algorithm 537, 538, 558iterating 82iteration 182, 184Iterative factorial solution 183iterative model 688iterative solution 176, 184<iterator> header 141, 540, 542iterator 198, 475, 607, 608iterator 479, 480, 481, 484, 503, 608iterator invalidation 519iterator operations 484iterator pointing to first element past the

end of container 480iterator pointing to the first element of the

container 480iterator typedef 483iterator-category hierarchy 483

JJacobson, Ivar 684Jacopini, G. 70Java programming language 16Jobs, Steve 16justified field 435

Kkey 500keyboard 9, 27, 115, 417, 419, 445Keypad class (ATM case study) 690, 693,

695, 708, 715, 716, 720, 728key–value pair 477, 505, 507, 508keywords 72

and 668

keywords (cont.)and_eq 669auto 213bitand 669bitor 669class 173, 583compl 669const 163enum 149enum class 150enum struct 150explicit 52, 339extern 154inline 163mutable 663namespace 665, 667not 668not_eq 668or 668or_eq 669private 47public 39static 154table of keywords 72template 583throw 566typedef 418typename 173, 583void 40xor 669xor_eq 669

Llabel 155labels in a switch structure 155lambda expression 518, 556lambda function 556lambda introducer 557large object 166last-in, first-out (LIFO) 158

data structure 477, 509order 582, 587

late binding 384leading 0 436leading 0x and leading 0X 432, 436left brace ({) 21, 24left justification 110, 434left-shift operator (<<) 304, 621, 621,

627, 628left side of an assignment 128, 187, 276,

328left stream manipulator 110, 432, 433,

433left-to-right associativity 98left value 128left-shift assignment operator (<<=) 629left-shift operator (<<) 419left-to-right associativity 35left-to-right evaluation 29, 30legacy C code 792legacy code 797length member function of class

string 593length of a string 254length of a substring 340length_error exception 493, 578, 599less function object 554less_equal function object 554

less< double > 505less< int > 501, 505less-than operator 32, 480less-than-or-equal-to operator 32lexicographical 597lexicographical_compare algo-

rithm 522, 524, 559lifeline of an object in a UML sequence

diagram 719LIFO (last-in, first-out) 158, 477, 509

order 582, 587<limits> header 141line 30line number 796line of communication with a file 448,

450line of text 424__LINE__ predefined symbolic constant

796link 6linkage 152, 667linker 7Linux 15

shell prompt 9Linux operating system 15<list> header 140list class 485, 494list functions

assign 498merge 498pop_back 498pop_front 498push_front 497remove 498sort 497splice 497swap 498unique 498

<list> header 494list initialization 94list initializer 227, 271

dynamically allocated array 322vector 490

literalfloating point 89

live-code approach xxiiiload 6loader 8, 8local automatic object 275local variable 44, 154, 156<locale> header 141log function 132log10 function 132logarithm 132logic error 6, 32logic_error exception 578logical AND 668logical AND (&&) 123logical negation 123, 124logical NOT (!) 123, 124, 668logical operator keywords 668logical operators 123logical OR (||) 123, 124, 626, 668logical_and function object 554logical_not function object 554logical_or function object 554long data type 120long double data type 138long int 177

810 Index

long int data type 120, 139long long data type 120, 138long long int data type 138loop 72, 79loop-continuation condition 72, 101,

102, 104, 105, 110, 111loop counter 101loop-continuation condition fails 182looping statement 72loss of data 442lower_bound algorithm 548, 558lower_bound function of associative

container 503lowercase letter 634, 636lowercase letters 26, 140“lowest type” 138low-level I/O capabilities 417lvalue ("left value") 128, 167, 187, 231,

232, 276, 328, 335, 500lvalues as rvalues 128

Mm-by-n array 211Mac OS X 15, 16machine code 110machine dependent 247machine language 153Macintosh 16macro 139macro argument 793macro definition 796macro expansion 793macro-identifier 792macros 791magnitude 434magnitude right justified 432main 21, 24“make your point” 146make_heap algorithm 550, 559make_pair 507mandatory function prototypes 137mangled function name 171manipulating individual characters 633manipulator 109manipulators 446many-to-one relationship 697<map> header 140, 505, 507mapped values 500mask 623“masked off” 623matching catch block 564math library 140math library functions 109, 131

ceil 131cos 131exp 131fabs 131floor 131fmod 131log 132log10 132pow 132sin 132sqrt 132tan 132

mathematical algorithms 529mathematical algorithms of the Standard

Library 529

max algorithm 552, 559max_element algorithm 529, 532, 559max_sizemember function of a string

601max_size member function of contain-

ers 478maximum function 132maximum length of a string 601maximum size of a string 599mean 30member function 4, 38, 39, 726

argument 41implementation in a separate source-

code file 59parameter 41

member function automatically inlined261

member function call 5member function calls for const objects

281member function calls often concise 262member function defined in a class defini-

tion 261member function definitions of class In-

teger 576member functions that take no arguments

262member-initializer list 52, 283, 286, 675member object

default constructor 288initializer 287

member selection operator (.) 265, 293,384, 576

memberwise assignment 279, 308memberwise copy 332memchr 656, 658memcmp 656, 657memcpy 655, 656memmove 656, 657<memory> header 140memory 153memory address 229memory consumption 407memory functions of the string-handling

library 655memory handling

function memchr 658function memcmp 658function memcpy 656function memmove 657function memset 659

<memory> header 575memory leak 322, 476, 575, 577, 607

prevent 577memory-access violation 476memset 656, 659merge algorithm 538, 540, 558merge in the UML 705merge member function of list 498merge symbol 79message in the UML 714, 716, 717, 720message passing in the UML 719Microsoft

Visual C++ 6Microsoft Visual C++ 669Microsoft Windows 116min algorithm 552, 559min_element algorithm 529, 532, 559minmax algorithm 552, 559

minmax_element algorithm 529, 532,553, 559

minus function object 554minus sign (-) indicating private visibility

in the UML 726minus sign, – (UML) 50mismatch algorithm 522, 524, 558mission-critical computing 565mixed-type expression 138model of a software system 694, 702, 735modifiable lvalue 308, 328, 335modify a constant pointer 243modify address stored in pointer variable

243modulus function object 554modulus operator (%) 28, 29, 142, 146monetary formats 141most derived class 681move algorithm 540, 558move assignment operator 334, 480move constructor 334, 370, 478, 480move semantics 334, 480move_backward algorithm 540, 558Mozilla Foundation 15multidimensional array 211multimap associative container 505multiple 28multiple inheritance 345, 418, 672, 673,

674, 675, 677multiple inheritance demonstration 673multiple parameters to a function 44multiple-selection statement 72, 112multiple-source-file program

compilation and linking process 62multiple-statement body 34multiplication 28, 29multiplicative operators (*, /, %) 90multiplicity 694multiplies function object 554mutable

data member 663, 663, 664demonstration 664keyword 152, 663

mutable data member 664mutating sequence algorithms 558mutator 49

Nname decoration 171name function of class type_info 413name handle 264

on an object 264name mangling 171name mangling to enable type-safe link-

age 172name of a control variable 101name of a source file 796name of a user-defined class 39name of a variable 152name of an array 187named constant 191namespace 22

alias 668global 667nested 667qualifier 668unnamed 667

Index 811

namespace 665namespace alias 668namespace keyword 665, 667namespace member 665namespace scope 155namespaces 665naming conflict 291, 665narrowing conversion 95natural logarithm 132navigability arrow in the UML 726NDEBUG 797near container 477negate function object 554nested blocks 155nested control statement 92nested for statement 194, 214, 219nested if…else statement 76, 77nested message in the UML 718nested namespace 667nested namespace 667nested parentheses 29NetBeans 7network connection 417network message arrival 570new 332new calls the constructor 321new failure handler 574<new> header 572new operator 321new returning 0 on failure 573new stream manipulators 430new throwing bad_alloc on failure 572,

573newline ('\n') escape sequence 22, 28,

35, 118, 252, 421, 637next_permutation algorithm 559NeXTSTEP operating system 16noboolalpha stream manipulator 438noexcept keyword 571non-const member function 282non-const member function called on a

const object 282non-const member function on a non-

const object 282nonconstant pointer to constant data 241nonconstant pointer to nonconstant data

241noncontiguous memory layout of a deque

499nondeterministic random numbers 144none_of algorithm 533, 536, 558nonfatal logic error 32nonfatal runtime error 9non-member, friend function 313non-member function to overload an op-

erator 336nonmodifiable function code 264nonmodifiable lvalue 226, 308nonmodifying sequence algorithms 557,

558nonparameterized stream manipulator 90nonrecoverable failures 442non-staticmember function 291, 301,

337nontype template parameter 589nonzero treated as true 127noshowbase stream manipulator 432,

436noshowpoint stream manipulator 432

noshowpos stream manipulator 432, 434noskipws stream manipulator 432NOT (!; logical NOT) 123not equal 32not operator keyword 668not_eq operator keyword 668not_equal_to function object 554note 71nothrow object 573nothrow_t type 573noun phrase in requirements specification

692, 698nouppercase stream manipulator 432,

438nth_element algorithm 558NULL 231null character ('\0') 253, 254, 426, 640,

645null pointer (0) 230, 232, 449, 639null statement 78null terminated 606null-terminated string 255, 421nullptr constant 230number of arguments 136number of elements in an array 245<numeric> 532numeric algorithms 553, 559<numeric> header 559numerical data type limits 141

Oobject 2, 3object (or instance) 5, 717object code 7, 62object leaves scope 272object of a derived class 377, 380object of a derived class is instantiated 369object-oriented analysis and design

(OOAD) 6, 683object-oriented design (OOD) 683, 690,

692, 698, 702, 707, 726object-oriented language 6object-oriented programming (OOP) 2,

6, 16, 258, 343, 2object serialization 473object’s vtable pointer 410Objective-C 16objects contain only data 264oct stream manipulator 427, 432, 436octal (base-8) number system 427, 432,

649octal number 421, 436, 634, 650octal number system (base 8) 781off-by-one error 104offset 410offset from the beginning of a file 452offset to a pointer 250ofstream 446, 448, 450, 451, 461, 464,

466constructor 448open function 448

one’s complement 627, 788one’s complement operator (~) 621one-pass algorithm 482ones position 781one-to-many mapping 477one-to-many relationship 505, 697one-to-one mapping 477, 507

one-to-one relationship 697OOAD (object-oriented analysis and de-

sign) 6, 683OOD (object-oriented design) 683, 690,

692, 698, 702, 707OOP (object-oriented programming) 2,

6, 343open a file for input 448open a file for output 448open a nonexistent file 449open function of ofstream 448Open Handset Alliance 16open source 15, 16opened 445operand 22, 27, 28, 75operating system 15, 16operation (UML) 41operation compartment in a class diagram

708operation in the UML 41, 694, 707, 708,

711, 728, 731, 736operation parameter in the UML 44, 708,

711, 712operator

associativity 126overloading 28, 173, 304, 416, 621precedence 29, 98, 126, 629precedence and associativity chart 35

operator keywords 669operator keywords 308, 668, 669operator keywords demonstration 669operator overloading

decrement operators 315increment operators 315

operator void* 452operator void* member function 442operator void* member function of

ios 449operator! member function 314, 442,

449operator!= 335operator() overloaded operator 553operator[]

const version 335non-const version 335

operator+ 308operator++ 315, 321operator++( int ) 315operator<< 313, 331operator= 333, 478operator== 334, 523operator>> 312, 331operators

! (logical NOT operator) 123, 124!= (inequality operator) 32.* and ->* 670() (parentheses operator) 29* (multiplication operator) 29* (pointer dereference or indirection)

232, 232*= multiplication assignment 96/ (division operator) 29/= division assignment 96&& (logical AND operator) 123% (modulus operator) 29%= modulus assignment 96+ (addition operator) 27, 29+= 595+= addition assignment 95

812 Index

operators (cont.)< (less-than operator) 32<< (stream insertion operator) 22, 28<= (less-than-or-equal-to operator)

32= (assignment operator) 27, 29, 125-= subtraction assignment 96== (equality operator) 32, 125> (greater-than operator) 32>= (greater-than-or-equal-to opera-

tor) 32|| (logical OR operator) 123, 124addition assignment (+=) 95address (&) 232arithmetic 95arrow member selection (->) 265assignment 95conditional (?:) 75const_cast 661decrement (--) 96, 97delete 321dot (.) 40increment (++) 96member selection (.) 265multiplicative (*, /, %) 90new 321parentheses (()) 90postfix decrement 96postfix increment 96, 98prefix decrement 96prefix increment 96, 98scope resolution (::) 60sizeof 244, 245static_cast 90ternary 75typeid 413unary minus (-) 90unary plus (+) 90unary scope resolution (::) 169

optimizations on constants 281optimizing compiler 110, 154OR (||; logical OR) 123or operator keyword 668or_eq operator keyword 669order in which constructors and destruc-

tors are called 274order in which destructors are called 272order in which operators are applied to

their operands 180order of evaluation 181ordered associative containers 476, 500original format settings 440OS X 16ostream 452, 457, 466, 473ostream class 418

seekp function 452tellp function 452

ostream_iterator 481ostringstream class 609other character sets 592out-of-range array subscript 570out-of-range element 328out of scope 158out_of_bounds exception 493out_of_range class 335out_of_range exception 493, 514, 578,

595out_of_range exception class 226outer block 155

outer for structure 214out-of-bounds array elements 198output a floating-point value 432output buffering 443output data items of built-in type 419output format of floating-point numbers

437output iterator 482, 484, 521, 529, 542,

545output of char * variables 421output of characters 420output of floating-point values 421output of integers 421output of standard data types 420output of uppercase letters 421output sequence 481output stream 492output to string in memory 140outputting to strings in memory 609overflow 570overflow_error exception 578overhead of a function call 793overload the addition operator (+) 308overload unary operator ! 314overloaded [] operator 328overloaded << operator 314overloaded addition assignment operator

(+=) 316overloaded assignment (=) operator 327,

333overloaded binary operators 309overloaded cast operator function 337overloaded constructors 371overloaded equality operator (==) 327,

334overloaded function 171, 589overloaded function call operator () 340overloaded function definitions 170overloaded increment operator 316overloaded inequality operator 327, 335overloaded operator

() 553overloaded operator += 320overloaded operator[] member func-

tion 335overloaded postfix increment operator

316, 320overloaded prefix increment operator

316, 320overloaded stream insertion and stream

extraction operators 311overloaded stream insertion operator 675overloaded subscript operator 328, 335overloading 28, 170

constructor 271overloading + 309overloading << and >> 173overloading binary operator < 310overloading binary operators 309overloading function call operator () 340overloading operators 173overloading postfix increment operator

315, 321overloading prefix and postfix decrement

operators 315overloading prefix and postfix increment

operators 315overloading resolution 589

overloading stream insertion and streamextraction operators 310, 316, 320,327, 331

overloading template functions 589overloading the stream insertion operator

473override a function 383override keyword 384

Ppad with specified characters 421padding 633padding characters 429, 432, 433, 435padding in a structure 633pair 503pair of braces {} 34, 66parameter 41, 43parameter in the UML 44, 708, 711, 712parameter list 43, 52parameterized stream manipulator 90,

109, 418, 427, 452parameterized type 582parentheses operator (()) 29, 90parentheses to force order of evaluation

35partial_sort algorithm 558partial_sort_copy algorithm 558partial_sum algorithm 559partition algorithm 558partition_copy algorithm 558partition_point algorithm 558Pascal case 39pass-by-reference 164, 229, 235, 237

with a pointer parameter used to cubea variable’s value 235

with pointer parameters 233with reference parameters 165, 233

pass-by-reference with pointers 166pass-by-value 164, 165, 233, 234, 236,

243used to cube a variable’s value 234

passing arguments by value and by refer-ence 165

passing large objects 166passing options to a program 240“past the end” iterator 532peek function of istream 425percent sign (%) (modulus operator) 28perform a task 40perform an action 22performance 3PI 792, 793plus function object 554plus sign 434plus sign (+) indicating public visibility in

the UML 726plus sign, + (UML) 41pointer 247pointer 479pointer arithmetic 247, 248, 250, 489

machine dependent 247pointer assignment 249pointer-based strings 252pointer comparison 249pointer dereference (*) operator 232pointer expression 247, 250pointer handle 264pointer manipulation 407

Index 813

pointer notation 251pointer operators & and * 232pointer to a function 407pointer to an object 242pointer to void (void *) 249pointer variable 575pointer/offset notation 250pointer/subscript notation 250pointer-based string 606pointers and array subscripting 249, 250pointers and arrays 249pointers declared const 243pointers to dynamically allocated storage

293, 334pointer-to-member operators

.* 670->* 670

point-of-sale system 456poll analysis program 196polymorphic exception processing 572polymorphic programming 390, 410polymorphic screen manager 376polymorphically invoking functions in a

derived class 678polymorphism 373, 375polymorphism and references 407polynomial 31pop 587pop function of container adapters 509pop member function of

priority_queue 512pop member function of queue 511pop member function of stack 509pop_backmember function of list 498pop_front 494, 495, 500, 511pop_heap algorithm 551, 559Portability Tips overview xxivportable 2position number 186positional notation 781positional value 781, 782positional values in the decimal number

system 782postdecrement 96, 98postfix decrement operator 96postfix increment operator 96, 98postincrement 96, 320postincrement an iterator 484pow function 108, 110, 132power 132precedence 29, 31, 35, 98, 104, 124, 180precedence chart 35precedence not changed by overloading

309precedence of the conditional operator 75precision 90, 421, 426

format of a floating-point number 91precision function of ios_base 427precision of a floating-point value 85precision of floating-point numbers 427precision setting 428predecrement 96, 98predefined function objects 553predefined symbolic constants 796predicate function 265, 497, 523, 526,

529, 532, 536, 537, 540, 545, 550prefix decrement operator 96, 97prefix increment operator 96, 98preincrement 96, 320

preprocessing directives 7, 21preprocessor 6, 7, 137, 791preprocessor directives

#ifndef 259#define 259#endif 259

prev_permutation algorithm 559prevent memory leak 577preventing headers from being included

more than once 259primary memory 8primitive data type promotion 90principal 108principle of least privilege 153, 239, 240,

243, 281, 450, 483print a line of text 20printer 9, 417printing

line of text with multiple statements23

multiple lines of text with a singlestatement 24

unsigned integer in bits 622priority_queue adapter class 512

empty function 513pop function 512push function 512size function 513top function 513

privateaccess specifier 47, 726base class 372base-class data cannot be accessed

from derived class 358inheritance 345members of a base class 345static data member 298

private libraries 7probability 141program development environment 6program execution stack 159program in the general 375program in the specific 375program termination 275, 276programmer-defined function

maximum 132promotion 90promotion hierarchy for built-in data

types 138promotion rules 138prompt 27, 88prompting message 443proprietary classes 372protected 361protected access specifier 258protected base class 372protected base-class data can be ac-

cessed from derived class 363protected inheritance 345, 372pseudorandom numbers 144public

keyword 726, 731method 260

public access specifier 39public base class 372public inheritance 343, 345public keyword 39public member of a derived class 346public services of a class 58

public static class member 298public static member function 298punctuation mark 644pure specifier 391pure virtual function 391, 407push 587push function of container adapters 509push member function of

priority_queue 512push member function of queue 511push member function of stack 509push_back member function of class

template vector 227push_backmember function of vector

488push_frontmember function of deque

499push_front member function of list

497push_heap algorithm 551, 559put file-position pointer 457, 462put member function 421, 422put pointer 452putback function of istream 425

Qqualified name 369<queue> header 140queue adapter class 511

back function 511empty function 511front function 511pop function 511push function 511size function 511

<queue> header 511, 512quotation marks 22

Rradians 131raise to a power 132rand function 141, 142RAND_MAX symbolic constant 141random integers in range 1 to 6 142random number 144random_shuffle algorithm 529, 531,

558random-access file 445, 457, 458, 464,

466random-access iterator 482, 483, 498,

501, 518, 524, 531, 536, 550, 551random-access iterator operations 484randomizing 144randomizing the die-rolling program 145range 481, 532range checking 324, 595range-based for 595, 608range-based for statement 200Rational Software Corporation 690Rational Unified Process™ 690raw data 456raw data processing 445rbegin member function of class

string 608rbegin member function of containers

479rbeginmember function of vector 490

814 Index

rdstate function of ios_base 442read 457, 464read a line of text 43read characters with getline 43read data sequentially from a file 450read function of istream 425read member function 426readmember function of istream 457,

471read-only variable 191Reading a random-access file sequentially

464Reading and printing a sequential file 450real number 85record 446, 466record format 459recover from errors 442recursion 175, 182, 183recursion step 176, 179recursive call 176, 179recursive function 175recursive function factorial 178recursive solution 184redundant parentheses 31, 123reference 229, 416, 479reference argument 233reference parameter 164, 165, 165reference to a constant 166reference to a private data member 276reference to an automatic variable 167reference to an int 165referencing array elements 251referencing array elements with the array

name and with pointers 251register declaration 154register storage-class specifier 152regular expression 17, 609reinterpret_cast operator 249, 458,

461, 464reinventing the wheel 3relational operator 32, 33relational operators >, <, >=, and <= 122release dynamically allocated memory 333remainder after integer division 28remove algorithm 526, 558remove member function of list 498remove_copy algorithm 524, 526, 558remove_copy_if algorithm 524, 527,

541, 558remove_if algorithm 524, 526, 558rend member function of class string

608rend member function of containers 479rend member function of vector 490repetition

counter controlled 79, 88repetition statement 70, 73

do…while 110, 111for 102, 104while 78, 102, 110

repetition terminates 78replace 603replace == operator with = 127replace algorithm 527, 529, 558replace member function of class

string 603, 605replace_copy algorithm 527, 529, 558replace_copy_if algorithm 527, 529,

558

replace_if algorithm 527, 529, 558replacement text 793, 796

for a macro or symbolic constant792, 794

requirements 5, 683, 688requirements document 688, 689requirements gathering 688requirements specification 684reset 514resize member function of class

string 601resource leak 572restore a stream’s state to “good” 442resumption model of exception handling

565rethrow an exception 567return a result 137Return key 27return message in the UML 720return statement 23, 47, 137, 176return type 40

void 40, 48return type in a function header 137return type in the UML 708, 713returning a reference from a function 167returning a reference to a private data

member 276reusability 582reusable software components 3reuse 4, 54, 264reverse algorithm 538, 541, 558reverse_copy algorithm 541, 542, 558reverse_iterator 479, 480, 484,

490, 608rfindmember function of class string

603right brace (}) 21, 23, 89right justification 110, 432, 433right operand 22right shift (>>) 621right shift operator (>>) 304right shift with sign extension assignment

operator (>>=) 629right stream manipulator 110, 432, 433right-to-left associativity 98right value 128rightmost (trailing) arguments 167right-shift operator (>>) 419, 621, 622,

628right-shifting a signed value is machine

dependent 629right-to-left associativity 35Ritchie, Dennis 2robust application 561, 565role in the UML 695role name in the UML 695rolling a die 142rolling a six-sided die 6000 times 143rolling two dice 146, 147rotate algorithm 558rotate_copy algorithm 558round a floating-point number for display

purposes 91rounded rectangle (for representing a state

in a UML state diagram) 703rounding numbers 91, 131row subscript 211rows 211

RTTI (runtime type information) 411,414

rules of operator precedence 29Rumbaugh, James 684runtime error 9runtime type information (RTTI) 411,

414runtime_error class 562, 570, 578

what function 567rvalue ("right value") 128, 167, 328

SSalariedEmployee class header 397SalariedEmployee class implementa-

tion file 398savings account 108scaling 142scaling factor 142, 146scientific notation 91, 421, 437scientific notation floating-point value

438scientific stream manipulator 432,

437scope 104, 155, 665scope of a symbolic constant or macro

794scope of an identifier 152, 154scope resolution operator (::) 60, 298,

585, 665, 668, 672, 677scoped enum 150scope-resolution operator (::) 150scopes

class 155file 155function 155function prototype 155namespace 155

scoping example 156screen 9, 21Screen class (ATM case study) 693, 695,

708, 714, 715, 716, 718, 720, 728screen-manager program 376scrutinize data 259search algorithm 558search functions of the string-handling li-

brary 651search key 500search_n algorithm 558searching 533searching arrays 209searching blocks of memory 655searching strings 639, 646second data member of pair 503second-degree polynomial 31secondary storage device 445secondary storage devices

CD 445DVD 445flash drive 445hard disk 445tape 445

second-degree polynomial 31“secret” implementation details 663security flaws 198seed 146seed function rand 144seek direction 452seek get 452

Index 815

seek put 452seekg function of istream 452, 472seekp function of ostream 452, 462select a substring 340selection statement 70, 73self assignment 333self-assignment 293self-documenting 26semicolon (;) 22, 34, 78, 791semicolon that terminates a structure def-

inition 617send a message to an object 5sentinel value 85, 89, 116separate interface from implementation

58sequence 210, 481, 538, 540sequence container 476, 483, 485, 493,

497back function 492empty function 493front function 492insert function 493

sequence diagram in the UML 691, 716sequence of messages in the UML 717sequence of random numbers 144sequence statement 70, 71, 73sequence-statement activity diagram 71sequential execution 70sequential file 445, 446, 447, 450, 456serialized object 473services of a class 49<set> header 140set a value 49set and get functions 48set associative container 504set function 288<set> header 501, 504set_intersection 545set_new_handler function 572, 574set of recursive calls to method Fibonac-

ci 181set operations of the Standard Library

543set_difference algorithm 543, 545,

559set_intersection algorithm 543,

545, 559set_new_handler specifying the func-

tion to call when new fails 574set_symmetric_difference algo-

rithm 543, 545, 559set_union algorithm 543, 546, 559setbase stream manipulator 427setfill stream manipulator 261, 433,

435setprecision stream manipulator 90,

109, 427setw 189, 312setw parameterized stream manipulator

109setw stream manipulator 254, 429, 433Shape class hierarchy 345shell prompt on Linux 9shift a range of numbers 142shifted, scaled integers 142shifted, scaled integers produced by 1 +

rand() % 6 142shiftingValue 146short-circuit evaluation 124

short data type 120short int data type 120showbase stream manipulator 432, 436showpoint stream manipulator 91, 432showpos stream manipulator 432, 434shrink_to_fit member function of

classes vector and deque 490shuffle algorithm 558shuffling algorithm 619side effect 164side effect of an expression 154, 164, 181sign extension 622sign left justified 432signal value 85signature 137, 171, 315signatures of overloaded prefix and postfix

increment operators 315significant digits 433simple condition 122, 124sin function 132sine 132single-argument constructor 339, 340single-entry/single-exit control statement

73, 74single inheritance 345, 677single-line comment 21single-precision floating-point number 89single quote 23single quote (') 252single-selection if statement 72, 76singly linked list 476, 494six-sided die 142size function of string 461size member function of array 187size member function of class string

64, 593size member function of containers 478size member function of

priority_queue 513size member function of queue 511size member function of stack 509size member function of vector 224size of a string 599size of a variable 152size of an array 244size_t 189, 458size_t type 244size_type 480sizeof 464, 651, 794sizeof operator 244, 245, 291

used to determine standard data typesizes 245

sizeof operator when applied to an ar-ray name returns the number of bytesin the array 245

skip remainder of switch statement 121skip remaining code in loop 122skipping whitespace 426, 432skipws stream manipulator 432small circle symbol 71smart pointer xxi, 18smartphone 16software engineering 58

data hiding 47, 49encapsulation 49reuse 54, 57separate interface from implementa-

tion 58set and get functions 48

Software Engineering Observations over-view xxiv

software life cycle 688software reuse 3, 343, 582, 672solid circle (for representing an initial

state in a UML diagram) in the UML703, 705

solid circle enclosed in an open circle (forrepresenting the end of a UML activitydiagram) 705

solid circle symbol 71solid diamonds (representing composi-

tion) in the UML 695sort algorithm 209, 533, 536, 558sort member function of list 497sort_heap algorithm 550, 559sorting 446, 533sorting and related algorithms 557sorting arrays 209sorting order 536, 540sorting strings 141source code 6, 372source-code file 54SourceForge 15spaces for padding 435space-time trade-off 466special character 253special characters 26specialization in the UML 734spiral 179splice member function of list 497splice_aftermember function of class

template forward_list 498sqrt function of <cmath> header 132square function 139square root 132, 428srand function 144srand( time( 0 ) ) 146<sstream> header 140, 609, 609stable_partition algorithm 558stable_sort algorithm 558<stack> header 140stack 158, 582stack adapter class 509

empty function 509pop function 509push function 509size function 509top function 509

Stack class template 582, 589stack frame 159<stack> header 509stack overflow 159, 176stack unwinding 566, 569, 571Stack< double > 585, 588stack<int> 588Stack<T> 587standard data type sizes 245standard error stream (cerr) 9standard exception classes 578standard input object (cin) 27standard input stream (cin) 9, 418standard input stream object (cin) 445Standard Library

class string 305container classes 476deque class template 499exception classes 579exception hierarchy 578

816 Index

Standard Library (cont.)headers 141, 791list class template 495map class template 508multimap class template 506multiset class template 501priority_queue adapter class 513queue adapter class templates 512set class template 504stack adapter class 509vector class template 487

standard output object (cout) 22, 418standard output stream (cout) 9standard output stream object (cout) 445standard stream libraries 418Standard Template Library 475state 690state bits 422state diagram for the ATM object 703state diagram in the UML 703state in the UML 690, 705state machine diagram in the UML 690,

703state of an object 698, 703statement 22, 40statement spread over several lines 35statement terminator (;) 22statements

break 118, 121continue 121do…while 110, 111for 102, 104if 32return 23switch 112, 119throw 261try 226while 102, 110

static array initialization 198, 199static array initialization and auto-

matic array initialization 199static binding 384static_cast<int> 116static data member 207, 297, 298static data member tracking the num-

ber of objects of a class 300static data members save storage 298static keyword 154static linkage specifier 667static local object 273, 275static local variable 156, 158, 198, 521static member 298static member function 298static storage class 152static storage duration 153, 154, 155static storage-class specifier 152static_cast 98, 126static_cast (compile-time type-

checked cast) 188static_cast operator 90status bits 442std namespace 592std::cin 27std::cout 21std::endl stream manipulator 28__STDC__ predefined symbolic constant

797<stdexcept> header 140, 562, 578StepStone 16

“sticky” setting 261sticky setting 110, 125STL 475STL algorithms

accumulate 553STL exception types 493stod function 612stof function 612stoi function 612stol function 612stold function 612stoll function 612storage alignment 617storage duration 152

automatic 153dynamic 153static 153thread 153

storage unit 633storage-class specifiers 152

extern 152mutable 152register 152static 152

storage-unit boundary 633stoul function 612stoull function 612str member function 610str member function of class ostring-

stream 609straight-line form 29, 30strcat function of header <cstring>

639, 641strchr 651strcmp function of header <cstring>

639, 642strcpy function of header <cstring>

639, 640strcspn 651, 652stream base 427stream extraction operator 419stream extraction operator >> ("get

from") 27, 34, 173, 304, 310, 332,419, 422, 473

stream I/O class hierarchy 446stream input 419, 422stream input/output 21stream insertion operator << ("put to")

22, 23, 28, 173, 304, 310, 332, 419,420, 449, 675

stream manipulator 28, 109, 426, 434,452

stream manipulators 90boolalpha 125, 438dec 427fixed 91, 437hex 427internal 434left 110, 433noboolalpha 438noshowbase 436noshowpoint 432noshowpos 432, 434nouppercase 432, 438oct 427right 110, 433scientific 437setbase 427setfill 261, 435

stream manipulators (cont.)setprecision 90, 109, 427setw 109, 254, 429showbase 436showpoint 91, 432showpos 434std::endl (end line) 28

stream of bytes 417stream of characters 22stream operation failed 442stream output 419<string> header 140string 477

size function 461string assignment 593, 594string assignment and concatenation

594string being tokenized 645string class 43, 304, 307, 593

at member function 308size member function 64substr member function 66, 307

string class copy constructor 592string class from the Standard Library

140string comparison 595string concatenation 593string constant 253string-conversion function 646

atof 647atoi 648atol 648strtod 649strtol 649strtoul 650

string find member function 601string find member functions 601<string> header 43, 592, 56string insert functions 605string insert member function 605string length 645string literal 22, 253string object

empty string 48initial value 48

string of characters 22string-search function

strchr 652strcspn 652strpbrk 653strrchr 653strspn 654strstr 655

string stream processing 609string::npos 603strings as full-fledged objects 252strlen function 640, 645strncat function 639, 641strncmp function 640, 642strncpy function 639, 640Stroustrup, B. 2strpbrk 651, 653strrchr 651, 653strspn 651, 654strstr 651, 654strtod 646, 648strtok function 640, 644strtol 647, 649, 649strtoul 647, 650

Index 817

struct 616structure 616, 792structure definition 616, 630structure members default to private

access 616structure name 616structure of a system 702, 703structure type 616structured programming 70student-poll-analysis program 196subclass 343subobject of a base class 678subproblem 176subscript 186subscript 0 (zero) 186subscript operator 500subscript operator [] 595subscript operator [] used with strings

593subscript operator for map 507subscript out of range 493subscript through a vector 493subscripted name used as an rvalue 328subscripting 498subscripting with a pointer and an offset

251substr 598substr member function of class

string 66, 598substrmember function of string 307substring 340substring length 340substring of a string 598subtract one pointer from another 247subtraction 29sum of the elements of an array 193summing integers with the for statement

107superclass 343survey 196, 198swap algorithm 538, 558swap member function of class string

598swap member function of containers 478swap member function of list 498swap_ranges algorithm 537, 538, 558swapping strings 598swapping two strings 598switch logic 390switch multiple-selection statement

112, 119switch multiple-selection statement ac-

tivity diagram with break statements120

symbol 592symbol values 781symbolic constant 791, 792, 794, 796symbolic constant NDEBUG 797symbolic constant PI 793synchronize operation of an istream and

an ostream 443synchronous call 717synchronous error 570system 690system behavior 690system requirements 688system structure 690

Ttab 35tab escape sequence \t 118Tab key 22tab stop 23table of values 211tablet computer 16tabular format 189tails 142tan function 132tangent 132tape 445tellg function of istream 452tellp function of ostream 452template 792

default type argument for a type pa-rameter 589

template definition 174template function 173template keyword 173, 583template parameter 583template parameter list 173temporary object 337temporary value 90, 139terminate a program 574terminate normally 449terminate successfully 23terminating condition 177terminating null character 253, 254, 607,

640, 645terminating right brace (}) of a block 155termination condition 198termination housekeeping 272termination model of exception handling

565termination test 182ternary conditional operator (?:) 181ternary operator 75test 514test characters 140test state bits after an I/O operation 422text editor 450text file 466text-printing program 20text substitution 793this pointer 291, 293, 301, 334this pointer used explicitly 291this pointer used implicitly and explicit-

ly to access members of an object 292thread storage duration 153throw an exception 226, 260, 261, 564throw exceptions derived from standard

exceptions 579throw exceptions not derived from stan-

dard exceptions 579throw keyword 566throw point 565throw standard exceptions 579tie an input stream to an output stream

443tilde character (~) 272Time class containing a constructor with

default arguments 266Time class definition 258Time class definition modified to enable

cascaded member-function calls 294Time class member-function definitions

259

Time class member-function definitions,including a constructor that takes ar-guments 267

time function 146__TIME__ predefined symbolic constant

797time source file is compiled 797to_string function 612token 640, 644tokenizing strings 639, 644tolower 634, 636top member function of

priority_queue 513top member function of stack 509total 154toupper 634, 636trailing return type 557trailing return type (function) 175trailing return types 175trailing zeros 432Transaction class (ATM case study)

733, 734, 735, 738, 772transaction processing 505transaction-processing program 466transaction-processing system 456transfer of control 70transform algorithm 529, 533, 558transition 71transition arrow 71, 74, 78, 79transition between states in the UML 703translation 7translation unit 667traversal 607trigonometric cosine 131trigonometric sine 132trigonometric tangent 132true 32true 73, 74, 75truncate 28, 83, 90, 448truncate fractional part of a double 138truth table 123

! (logical NOT) operator 125&& (logical AND) operator 123|| (logical OR) operator 124

try block 226, 564, 567, 570, 571try block expires 565try statement 226Turing Machine 70two-dimensional array 211, 215two-dimensional array manipulations

215two’s complement 788

notation 788twos position 783tying an output stream to an input stream

443type checking 793, 794type field 473type information 473type name (enumerations) 149type of a variable 152type of the this pointer 292type parameter 173, 583, 589type-safe linkage 171type_info class 413typedef 418, 592, 609, 618

fstream 420ifstream 420in first-class containers 479

818 Index

typedef (cont.)iostream 418istream 418ofstream 420ostream 418

typeid 413, 578<typeinfo> header 140, 413typename keyword 173, 583type-safe I/O 425

UUML (Unified Modeling Language) 6,

41, 683, 684, 690, 694, 701, 702, 733action expression 71action state 71activity diagram 70, 71, 78arrow 71attribute 41class diagram 41constructor in a class diagram 54data types 44decision symbol 74diagram 690diamond symbol 71, 74dotted line 71final state 71guard condition 74guillemets (« and ») 54initial state 71merge symbol 79minus sign (–) 50note 71plus sign (+) 41public operation 41Resource Center

(www.deitel.com/UML/) 691small circle symbol 71solid circle symbol 71String type 44transition 71transition arrow 71, 74, 78, 79

UML activity diagram 105solid circle (for representing an initial

state) in the UML 705solid circle enclosed in an open circle

(for representing the end of an ac-tivity) in the UML 705

UML class diagramattribute compartment 701constructor 54operation compartment 708

UML sequence diagramactivation 720arrowhead 720lifeline 719

UML state diagramrounded rectangle (for representing a

state) in the UML 703solid circle (for representing an initial

state) in the UML 703UML use case diagram

actor 689use case 689

unary decrement operator (--) 96unary increment operator (++) 96unary minus (-) operator 90unary operator 90, 124, 231unary operator overload 309, 314

unary plus (+) operator 90unary predicate function 497, 526, 529unary scope resolution operator (::) 169unbuffered output 420unbuffered standard error stream 418#undef preprocessing directive 794, 796undefined area in memory 618underflow_error exception 579underlying container 509underlying data structure 512underscore ( _ ) 26unformatted I/O 417, 418, 425unformatted output 420, 422Unicode 592Unicode character set 417Unified Modeling Language (UML) 6,

683, 684, 690, 694, 701, 702, 733uniform initialization 94uniform_int_distribution 151unincremented copy of an object 321unique algorithm 538, 540, 558unique keys 500, 504, 507unique member function of list 498unique_copy algorithm 541, 542, 558unique_ptr class 575

built-in array 578universal-time format 260UNIX 449unnamed bit field 633unnamed bit field with a zero width 633unnamed namespace 667unordered associative containers 476,

477, 500<unordered_map> header 140unordered_map class template 477, 507unordered_multimap class template

477, 505unordered_multiset class template

477, 501<unordered_set> header 140unordered_set class template 477, 504unscoped enum 150unsigned char data type 139unsigned data type 139, 145unsigned int 91unsigned int data type 139, 145unsigned int fundamental type 82unsigned integer in bits 622unsigned long 178, 650unsigned long data type 138unsigned long int 177, 178unsigned long int data type 138unsigned long long data type 138unsigned long long int 178unsigned long long int data type 138unsigned short data type 139unsigned short int data type 139untie an input stream from an output

stream 443unwinding the function call stack 568update records in place 456upper_bound algorithm 548, 558upper_bound function of associative

container 503uppercase letter 26, 140, 634, 636uppercase stream manipulator 432,

436, 438use case diagram in the UML 689, 690use case in the UML 688, 689

use case modeling 688user-defined class name 39user-defined function 132user-defined type 40, 149, 337using a dynamically allocated ostring-stream object 610

using a function template 173Using a static data member to maintain

a count of the number of objects of aclass 299

using an iterator to output a string 608using arrays instead of switch 195using declaration 34

in headers 56using directive 34, 665

in headers 56using function swap to swap twostrings 598

using Standard Library functions to per-form a heapsort 548

Using virtual base classes 680<utility> header 141utility function 265

Vvalidation 64validity checking 64value 27value initialize 238value of a variable 152value of an array element 187value_type 479variable 25variable name

argument 44parameter 44

variadic template 504<vector> header 140vector class 221

capacity function 488, 488crbegin function 490crend function 490push_back function 488push_front function 488rbegin function 490rend function 490

vector class template 186, 486push_back member function 227shrink_to_fit member function

490vector class template element-manipu-

lation functions 490<vector> header 221verb phrase in requirements specification

707vertical spacing 102vertical tab (‘v’) 634, 637vi 6virtual base class 661, 678, 679, 680,

681virtual destructor 389virtual function 375, 383, 407, 409,

678call 409call illustrated 408table (vtable) 407

virtual inheritance 679virtual memory 573, 574

Index 819

visibility in the UML 726visibility marker in the UML 726Visual Studio 2012 Express Edition 7void * 249, 655void keyword 40, 48void return type 138volatile qualifier 661volume of a cube 164vtable 407, 409, 410vtable pointer 410

W“walk off” either end of an array 323warning message 66waterfall model 688wchar_t 592wchar_t character type 418“weakest” iterator type 482, 519what member function of an exception

object 226what virtual function of class exception

562, 567, 573

while repetition statement 72, 78, 102,110

while statement activity diagram 79whitespace characters 21, 22, 35, 422,

423, 426, 634, 637, 791, 796whole/part relationship 695width implicitly set to 0 429width member function of class

ios_base 429width of a bit field 630width of random number range 146width setting 429Windows 15, 116Windows operating system 15Windows Phone 7 15Withdrawal class (ATM case study) 693,

694, 695, 696, 699, 700, 705, 708,715, 716, 719, 720, 728, 729, 731,733, 734, 735, 737, 738, 739

word 617word boundary 617workflow of a portion of a software system

71workflow of an object in the UML 704

Wozniak, Steve 16wraparound 320write 457, 462write function of ostream 421, 425writing data randomly to a random-access

file 462

XXcode 7Xerox PARC (Palo Alto Research Center)

16XML (extensible markup language) 473xor operator keyword 669xor_eq operator keyword 669

Zzeroth element 186zero-width bit field 633