Chapter 2. Introduction to C++ Programming

Images

Objectives

In this chapter, you’ll:

Write simple C++ applications.

Use input and output statements.

Use fundamental data types.

Use arithmetic operators.

Understand the precedence of arithmetic operators.

Write decision-making statements.

Use relational and equality operators.

Begin appreciating the “objects natural” learning approach by creating and using objects of the C++ standard library’s string class before creating your own custom classes.

2.1 Introduction

This chapter presents several code examples that demonstrate how your programs can display messages and obtain data from the user for processing. The first three display messages on the screen. The next obtains two numbers from a user at the keyboard, calculates their sum and displays the result—the accompanying discussion introduces C++’s arithmetic operators. The fifth example demonstrates decision making by showing you how to compare two numbers, then display messages based on the comparison results.

“Objects Natural” Learning Approach

In your programs, you’ll create and use many objects of carefully-developed-and-tested preexisting classes that enable you to perform significant tasks with minimal code. These classes typically come from:

• the C++ standard library,

• platform-specific libraries (such as those provided by Microsoft for creating Windows applications or by Apple for creating macOS applications) and

• free third-party libraries often created by the massive open-source communities that have developed around all major contemporary programming languages.

To help you appreciate this style of programming early in the book, you’ll create and use objects of preexisting C++ standard library classes before creating your own custom classes. We call this the “objects natural” approach. You’ll begin by creating and using string objects in this chapter’s final example. In later chapters, you’ll create your own custom classes. You’ll see that C++ enables you to “craft valuable classes” for your own use and that other programmers can reuse.

Compiling and Running Programs

For instructions on compiling and running programs in Microsoft Visual Studio, Apple Xcode and GNU C++, see the test-drives in Chapter 1 or our video instructions at

http://deitel.com/c-plus-plus-20-for-programmers
“Rough-Cut” E-Book for O’Reilly Online Learning Subscribers

You are viewing an early-access “rough cut” of C++20 for Programmers. We prepared this content carefully, but it has not yet been reviewed or copy edited and is subject to change. As we complete each chapter, we’ll post it here. Please send any corrections, comments, questions and suggestions for improvement to [email protected] and I’ll respond promptly. Check here frequently for updates.

“Sneak Peek” Videos for O’Reilly Online Learning Subscribers

As an O’Reilly Online Learning subscriber, you also have access to the “sneak peek” of our new C++20 Fundamentals LiveLessons videos at:

https://learning.oreilly.com/videos/c-20-fundamentals-parts/9780136875185

Co-author Paul Deitel immediately records each video lesson as we complete each rough-cut e-book chapter. Lessons go live on O’Reilly Online Learning a few days later. Again, check here frequently for updates.

2.2 First Program in C++: Displaying a Line of Text

Consider a simple program that displays a line of text (Fig. 2.1). The line numbers are not part of the program.

 1  // fig02_01.cpp
 2  // Text-printing program.
 3  #include <iostream> // enables program to output data to the screen
 4
 5  // function main begins program execution
 6  int main() {
 7     std::cout << "Welcome to C++!
"; // display message
 8
 9     return 0; // indicate that program ended successfully
10   } // end function main
Welcome to C++!

Fig. 2.1 Text-printing program.

Comments

Lines 1 and 2

// fig02_01.cpp
// Text-printing program.

each begin with //, indicating that the remainder of each line is a comment. In each of our programs, the first line comment contains the program’s file name. The comment "Text-printing program." describes the purpose of the program. A comment beginning with // is called a single-line comment because it terminates at the end of the current line. You can create multiline comments by enclosing them in /* and */, as in

/* fig02_01.cpp
   Text-printing program. */
#include Preprocessing Directive

Line 3

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

is a preprocessing directive—that is, a message to the C++ preprocessor, which the compiler invokes before compiling the program. This line notifies the preprocessor to include in the program the contents of the input/output stream header <iostream>. This header is a file containing information the compiler requires when compiling any program that outputs data to the screen or inputs data from the keyboard using C++’s stream input/output. The program in Fig. 2.1 outputs data to the screen. Chapter 5 discusses headers in more detail, and Chapter 15 explains the contents of <iostream> in more detail.

Blank Lines and White Space

Line 4 is simply a blank line. You use blank lines, spaces and tabs to make programs easier to read. Together, these characters are known as white space—they’re normally ignored by the compiler.

The main Function

Line 6

int main() {

is a part of every C++ program. The parentheses after main indicate that it’s a function. C++ programs typically consist of one or more functions and classes. Exactly one function in every program must be named main. Figure 2.1 contains only one function. C++ programs begin executing at function main. The keyword int to the left of main indicates that after main finishes executing, it “returns” an integer (whole number) value. Keywords are reserved by C++ for a specific use. We show the complete list of C++ keywords in Chapter 3. We’ll explain what it means for a function to “return a value” when we demonstrate how to create your own functions in Chapter 5. For now, simply include the keyword int to the left of main in each of your programs.

The left brace, {, (end of line 6) must begin each function’s body, which contains the instructions the function performs. A corresponding right brace, }, (line 10) must end each function’s body.

An Output Statement

Line 7

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

displays the characters contained between the double quotation marks. Together, the quotation marks and the characters between them are called a string, a character string or a string literal. We refer to characters between double quotation marks simply as strings. White-space characters in strings are not ignored by the compiler.

The entire line 7—including std::cout, the << operator, the string "Welcome to C++! " and the semicolon (;)—is called a statement. Most C++ statements end with a semicolon. Omitting the semicolon at the end of a C++ statement when one is needed is a syntax error. Preprocessing directives (such as #include) are not C++ statements and do not end with a semicolon.

Typically, output and input in C++ are accomplished with streams of data. When the preceding statement executes, it sends the stream of characters Welcome to C++! to the standard output stream object (std::cout), which is normally “connected” to the screen.

Indentation

Indent the body of each function one level within the braces that delimit the function’s body. This makes a program’s functional structure stand out, making the program easier to read. Set a convention for the size of indent you prefer, then apply it uniformly. The tab key may be used to create indents, but tab stops may vary. We prefer three spaces per level of indent.

The std Namespace

The std:: before cout is required when we use names that we’ve brought into the program by preprocessing directives like #include <iostream>. The notation std::cout specifies that we are using a name, in this case cout, that belongs to namespace std. The names cin (the standard input stream) and cerr (the standard error stream)—introduced in Chapter 1—also belong to namespace std. We discuss namespaces in Chapter 23, Other Topics. For now, you should simply remember to include std:: before each mention of cout, cin and cerr in a program. This can be cumbersome—we’ll soon introduce 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 Sequences

In a cout statement, the << operator is referred to as the stream insertion operator. 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 toward where the data goes. A string’s characters normally display exactly as typed between the double quotes. However, the characters are not displayed in Fig. 2.1’s sample output. The backslash () is called an escape character. It indicates that a “special” character is to be output. When a backslash is encountered in a string, the next character is combined with the backslash to form an escape sequence. The escape sequence means newline. It causes the cursor (i.e., the current screen-position indicator) to move to the beginning of the next line on the screen. Some common escape sequences are shown in the following table:

Images
The return Statement

Line 9

return 0; // indicate that program ended successfully

is one of several means we’ll use to exit a function. In this return statement at the end of main, the value 0 indicates that the program terminated successfully. If program execution reaches the end of main without encountering a return statement, C++ assumes that the program terminated successfully. So, we omit the return statement at the end of main in subsequent programs that terminate successfully.

2.3 Modifying Our First C++ Program

The next two examples modify the program of Fig. 2.1. The first displays text on one line using multiple statements. The second displays text on several lines using one statement.

Displaying a Single Line of Text with Multiple Statements

Figure 2.2 performs stream insertion in multiple statements (lines 7–8), yet produces the same output as Fig. 2.1. Each stream insertion resumes displaying where the previous one stopped. Line 7 displays Welcome followed by a space, and because this string did not end with , line 8 begins displaying on the same line immediately following the space.

 1  // fig02_02.cpp
 2  // Displaying a line of text with multiple statements.
 3  #include <iostream> // enables program to output data to the screen
 4
 5  // function main begins program execution
 6  int main() {
 7     std::cout << "Welcome "; 
 8     std::cout << "to C++!
";
 9  } // end function main
Welcome to C++!

Fig. 2.2 Displaying a line of text with multiple statements.

Displaying Multiple Lines of Text with a Single Statement

A single statement can display multiple lines by using additional newline characters, as in line 7 of Fig. 2.3. Each time the (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 your output, place two newline characters back to back, as in line 7.

 1  // fig02_03.cpp
 2  // Displaying multiple lines of text with a single statement.
 3  #include <iostream> // enables program to output data to the screen
 4
 5  // function main begins program execution
 6  int main() {
 7     std::cout << "Welcome
to

C++!
";
 8  } // end function main
Welcome
to

C++!

Fig. 2.3 Displaying multiple lines of text with a single statement.

2.4 Another C++ Program: Adding Integers

Our next program obtains two integers typed by a user at the keyboard, computes their sum and outputs the result using std::cout. Figure 2.4 shows the program and sample inputs and outputs. In the sample execution, the user’s input is in bold.

 1  // fig02_04.cpp
 2  // Addition program that displays the sum of two integers.
 3  #include <iostream> // enables program to perform input and output
 4
 5  // function main begins program execution
 6  int main() {
 7     // declaring and initializing variables
 8     int number1{0}; // first integer to add (initialized to 0)  
 9     int number2{0}; // second integer to add (initialized to 0) 
10     int sum{0}; // sum of number1 and number2 (initialized to 0)
11
12     std::cout << "Enter first integer: "; // prompt user for data
13     std::cin >> number1; // read first integer from user into number1
14
15     std::cout << "Enter second integer: "; // prompt user for data
16     std::cin >> number2; // read second integer from user into number2
17
18     sum = number1 + number2; // add the numbers; store result in sum
19
20     std::cout << "Sum is " << sum << std::endl; // display sum; end line
21   } // end function main
Enter first integer: 45
Enter second integer: 72
Sum is 117

Fig. 2.4 Addition program that displays the sum of two integers.

Variable Declarations and List Initialization

Lines 8–10

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)

are declarationsnumber1, number2 and sum are the names of variables. These declarations specify that the variables number1, number2 and sum are data of type int, meaning that these variables will hold integer (whole number) values, such as 7, –11, 0 and 31914. All variables must be declared with a name and a data type.

11 Lines 8–10 initialize each variable to 0 by placing a value in braces ({ and }) immediately following the variable’s name—this is known as list initialization, which was introduced in C++11. Although it’s not always necessary to initialize every variable explicitly, doing so will help you avoid many kinds of problems.

Prior to C++11, lines 8–10 would have been written as:

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)

If you work with legacy C++ programs, you’re likely to encounter initialization statements using this older C++ coding style. In subsequent chapters, we’ll discuss various list initialization benefits.

Declaring Multiple Variables at Once

Several variables of the same type may be declared in one declaration—for example, we could have declared and initialized all three variables in one declaration by using a comma-separated list as follows:

int number1{0}, number2{0}, sum{0};

But, this makes the program less readable and makes it awkward to provide comments that describe each variable’s purpose.

Fundamental Types

We’ll soon discuss the type double for specifying real numbers and the type char for specifying 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, uppercase letter, digit or special character (e.g., $ or *). Types such as int, double and char are called fundamental types. Fundamental-type names consist of one or more keywords and must appear in all lowercase letters. For a complete list of C++ fundamental types and their typical ranges, see

https://en.cppreference.com/w/cpp/language/types
Identifiers

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

C++ allows identifiers of any length, but some C++ implementations may restrict identifier lengths. Do not use identifiers that begin with underscores and double underscores, because C++ compilers use names like that for their own purposes internally.

Placement of Variable Declarations

Variable declarations can be placed almost anywhere in a program, but they must appear before the variables are used. For example, the declaration in line 8

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

could have been placed immediately before line 13

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

the declaration in line 9

int number2{0}; // second integer to add (initialized to 0)

could have been placed immediately before line 16

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

and the declaration in line 10

int sum{0}; // sum of number1 and number2 (initialized to 0)

could have been placed immediately before line 18

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

In fact, lines 10 and 18 could have been combined into the following declaration and placed just before line 20:

int sum{number1 + number2}; // initialize sum with number1 + number2
Obtaining the First Value from the User

Line 12

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

displays Enter first integer: followed by a space. This message is called a prompt because it directs the user to take a specific action. Line 13

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

uses the standard input stream object cin (of namespace std) and the stream extraction operator, >>, to obtain a value from the keyboard.

When the preceding statement executes, the computer waits for the user to enter a value for variable number1. The user responds by typing an integer (as characters), then pressing the Enter key (sometimes called the Return key) to send the characters to the computer. The computer converts the character representation of the number to an integer value and assigns this value to the variable number1. Pressing Enter also causes the cursor to move to the beginning of the next line on the screen.

When your program is expecting the user to enter an integer, the user could enter alphabetic characters, special symbols (like # or @) or a number with a decimal point (like 73.5), among others. In these early programs, we assume that the user enters valid data. We’ll present various techniques for dealing with data-entry problems later.

Obtaining the Second Value from the User

Line 15

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

displays Enter second integer: on the screen, prompting the user to take action. Line 16

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

obtains a value for variable number2 from the user.

Calculating the Sum of the Values Input by the User

The assignment statement in line 18

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

adds the values of variables number1 and number2 and assigns the result to variable sum using the assignment operator =. Most calculations are performed in assignment statements. The = operator and the + operator are binary operators because each has two operands. For the + operator, the two operands are number1 and number2. For the preceding = operator, the two operands are sum and the value of the expression number1 + number2. Placing spaces on either side of a binary operator makes the operator stand out and makes the program more readable.

Displaying the Result

Line 20

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

displays the character string "Sum is" followed by the numerical value of variable sum followed by std::endl—a stream manipulator. The name endl is an abbreviation for “end line” 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 outputs accumulate in the machine until there are enough to “make it worthwhile” to display them on the screen, std::endl forces any accumulated outputs to be displayed at that moment. This can be important when the outputs are prompting the user for an action, such as entering data.

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

Calculations can also be performed in output statements. We could have combined the statements in lines 18 and 20 into the statement

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

thus eliminating the need for the variable sum.

The signature feature of C++ is that you can create your own data types called classes (we discuss this in Chapter 10 and explore it in depth in Chapter 11). You can then “teach” C++ how to input and output values of these new data types using the >> and << operators, respectively. This is called operator overloading, which we explore in Chapter 14.

2.5 Arithmetic

The following table summarizes the arithmetic operators:

Images

Note the use of various special symbols not used in algebra. The asterisk (*) indicates multiplication and the percent sign (%) is the remainder operator, which we’ll discuss shortly. These arithmetic operators are all binary operators.

Integer Division

Integer division in which the numerator and the denominator are integers yields an integer quotient. For example, the expression 7/4 evaluates to 1, and the expression 17 / 5 evaluates to 3. Any fractional part in the result of integer division is truncated—no rounding occurs.

Remainder Operator

The remainder operator, %, yields the remainder after integer division and can be used only with integer operands—x % y yields the remainder after dividing x by y. Thus, 7%4 yields 3 and 17 % 5 yields 2.

Parentheses for Grouping Subexpressions

Parentheses 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 Precedence

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

1. Expressions in parentheses evaluate first. Parentheses are said to be at the “highest level of precedence.” In cases of nested or embedded parentheses, such as

(a * (b + c))

expressions in the innermost pair of parentheses evaluate first.

2. Multiplication, division and remainder operations evaluate next. If an expression contains several multiplication, division and remainder operations, they’re applied from left-to-right. These three operators are said to be on the same level of precedence.

3. Addition and subtraction operations evaluate last. If an expression contains several addition and subtraction operations, they’re applied from left-to-right. Addition and subtraction also have the same level of precedence.

Appendix A contains the complete operator precedence chart. 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 in which these parenthesized subexpressions will evaluate.

Operator Grouping

When we say that C++ applies certain operators from left-to-right, we are referring to the operators’ grouping. For example, in the expression

a + b + c

the addition operators (+) group from left-to-right as if we parenthesized the expression as (a+b)+ c. Most C++ operators of the same precedence group left-to-right. We’ll see that some operators group right-to-left.

2.6 Decision Making: Equality and Relational Operators

We now introduce C++’s if statement, which allows a program to take alternative action based on whether a condition is true or false. Conditions in if statements can be formed by using the relational operators and equality operators in the following table:

Images

The relational operators all have the same level of precedence and group left-to-right. The equality operators both have the same level of precedence, which is lower than that of the relational operators, and group left-to-right.

Reversing the order of the pair of symbols in the operators !=, >= and <= (by writing them as =!, => 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 at execution time. You’ll understand why when we cover logical operators in Chapter 4.

Confusing == and =

Confusing 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 assignment operator as “gets” or “gets the value of” or “is assigned the value of.” As you’ll see in Section 4.12, confusing these operators may not necessarily cause an easy-to-recognize syntax error, but may cause subtle logic errors.

Using the if Statement

Figure 2.5 uses six if statements to compare two integers input by the user. If a given if statement’s condition is true, the output statement in the body of that if statement executes. If the condition is false, the output statement in the body does not execute.

 1  // fig02_05.cpp
 2  // Comparing integers using if statements, relational operators
 3  // and equality operators.
 4  #include <iostream> // enables program to perform input and output
 5
 6  using std::cout; // program uses cout
 7  using std::cin; // program uses cin  
 8  using std::endl; // program uses endl
 9
10   // function main begins program execution
11   int main() {
12      int number1{0}; // first integer to compare (initialized to 0)
13      int number2{0}; // second integer to compare (initialized to 0)
14
15      cout << "Enter two integers to compare: "; // prompt user for data
16      cin >> number1 >> number2; // read two integers from user
17
18      if (number1 == number2) {                    
19         cout << number1 << " == " << number2 << endl;
20      }                                            
21
22      if (number1 != number2) {
23         cout << number1 << " != " << number2 << endl;
24      }
25
26      if (number1 < number2) {
27         cout << number1 << " < " << number2 << endl;
28      }
29
30      if (number1 > number2) {
31         cout << number1 << " > " << number2 << endl;
32      }
33
34      if (number1 <= number2) {
35         cout << number1 << " <= " << number2 << endl;
36      }
37
38      if (number1 >= number2) {
39         cout << number1 << " >= " << number2 << endl;
40      }
41   } // end function main
Enter two integers to compare: 3 7
3 != 7
3 < 7
3 <= 7
Enter two integers to compare: 22 12
22 != 12
22 > 12
22 >= 12
Enter two integers to compare: 7 7
7 == 7
7 <= 7
7 >= 7

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

using Declarations

Lines 6–8

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

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

using Directive

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

using namespace std;

which, when you include a C++ standard library header (such as <iostream>), enables your program to use any name from that header’s std namespace. From this point forward in the book, we’ll use this directive in our programs.1

1. In Chapter 23, Other Topics, we’ll discuss some issues with using directives in large-scale systems.

Variable Declarations and Reading the Inputs from the User

Lines 12–13

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

declare the variables used in the program and initialize them to 0.

Line 16

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

uses cascaded stream extraction operations to input two integers. Recall that we’re allowed to write cin (instead of std::cin) because of line 7. First, a value is read into number1, then a value is read into number2.

Comparing Numbers

The if statement in lines 18–20

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

determines whether the values of variables number1 and number2 are equal. If so, the cout statement displays a line of text indicating that the numbers are equal. For each condition that is true in the remaining if statements starting in lines 22, 26, 30, 34 and 38, the corresponding cout statement displays an appropriate line of text.

Braces and Blocks

Each if statement in Fig. 2.5 contains a single body statement that’s indented to enhance readability. Also, notice that we’ve enclosed each body statement in a pair of braces, { }, creating what’s called a compound statement or a block.

You don’t need to use braces, { }, around single-statement bodies, but you must include the braces around multiple-statement bodies. Forgetting to enclose multiple-statement bodies in braces leads to errors. To avoid errors, as a rule, always enclose an if statement’s body statement(s) in braces.

Common Logic Error: Placing a Semicolon After a Condition

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

Splitting Lengthy Statements

A lengthy statement may be spread over several lines. If a statement must be split across lines, choose meaningful breaking points, such as after a comma in a comma-separated list, or after an operator in a lengthy expression. If a statement is split across two or more lines, indent all subsequent lines and left-align the group of indented lines.

Operator Precedence and Grouping

With the exception of the assignment operator =, all the operators presented in this chapter group from left-to-right. Assignments (=) group from right-to-left. So, an expression such as x = y = 0 evaluates as if it had been written x = (y = 0), which first assigns 0 to y, then assigns the result of that assignment (that is, 0) to x.

Refer to the complete operator precedence chart in Appendix A when writing expressions containing many operators. Confirm that the operators in the expression are performed in the order you expect. If you’re uncertain about the order of evaluation in a complex expression, break the expression into smaller statements or use parentheses to force the order of evaluation, exactly as you’d do in an algebraic expression.

2.7 Objects Natural: Creating and Using Objects of Standard Library Class string

Throughout this book, we emphasize using preexisting valuable classes from the C++ standard library and various open-source libraries from the C++ open-source community. You’ll focus on knowing what libraries are out there, choosing the ones you’ll need for your applications, creating objects from existing library classes and making those objects exercise their capabilities. By Objects Natural, we mean that you’ll be able to program with powerful objects before you learn to create custom classes

You’ve already worked with C++ objects—specifically the cout and cin objects, which encapsulate the mechanisms for output and input, respectively. These objects were created for you behind the scenes using classes from the header <iostream>. In this section, you’ll create and interact with objects of the C++ standard library’s string2 class.

2. You’ll learn additional string capabilities in subsequent chapters. Chapter 8 discusses class string in detail, test-driving many more of its member functions.

Test-Driving Class string

Classes cannot execute by themselves. A Person object can drive a Car object by telling it what to do (go faster, go slower, turn left, turn right, etc.)—without knowing how the car’s internal mechanisms work. Similarly, the main function can “drive” a string object by calling its member functions—without knowing how the class is implemented. In this sense, main in the following program is referred to as a driver program. Figure 2.6’s main function test-drives several string member functions.

 1  // fig02_06.cpp
 2  // Standard Library string class test program.
 3  #include <iostream>
 4  #include <string>
 5  using namespace std;
 6
 7  int main() {
 8     string s1{"happy"};                  
 9     string s2{" birthday"};              
10     string s3; // creates an empty string
11
12     // display the strings and show their lengths (length is C++20)
13     cout << "s1: "" << s1 << ""; length: " << s1.length()
14        << "
s2: "" << s2 << ""; length: " << s2.length()
15        << "
s3: "" << s3 << ""; length: " << s3.length();
16
17     // compare strings with == and !=
18     cout << "

The results of comparing s2 and s1:" << boolalpha
19        << "
s2 == s1: " << (s2 == s1)
20        << "
s2 != s1: " << (s2 != s1);
21
22     // test string member function empty
23     cout << "

Testing s3.empty():
";
24
25     if (s3.empty()) {
26        cout << "s3 is empty; assigning to s3;
";
27        s3 = s1 + s2; // assign s3 the result of concatenating s1 and s2
28        cout << "s3: "" << s3 << """;
29     }
30
31     // testing new C++20 string member functions
32     cout << "

s1 starts with "ha": " << s1.starts_with("ha") << endl;
33     cout << "s2 starts with "ha": " << s2.starts_with("ha") << endl;
34     cout << "s1 ends with "ay": " << s1.ends_with("ay") << endl;
35     cout << "s2 ends with "ay": " << s2.ends_with("ay") << endl;
36   }
s1: "happy"; length: 5
s2: " birthday"; length: 9
s3: ""; length: 0

The results of comparing s2 and s1:
s2 == s1: false
s2 != s1: true

Testing s3.empty():
s3 is empty; assigning to s3;
s3: "happy birthday"

s1 starts with "ha": true
s2 starts with "ha": false
s1 ends with "ay": false
s2 ends with "ay": true

Fig. 2.6 Standard Library string class test program.

Instantiating Objects

Typically, you cannot call a member function of a class until you create an object of that class3—also called instantiating an object. Lines 8–10 create three string objects:

s1 is initialized with the string literal "happy",

s2 is initialized with the string literal " birthday" and

s3 is initialized by default to the empty string (that is, "").

3. You’ll see in Section 11.15 that you can call a class’s static member functions without creating an object of that class.

When we declare int variables, as we did earlier, the compiler knows what int is—it’s a fundamental type that’s built into C++. In lines 8–10, however, the compiler does not know in advance what type string is—it’s a class type from the C++ standard library.

When packaged properly, classes can be reused by other programmers. This is one of the most significant benefits of working with object-oriented programming languages like C++ that have rich libraries of powerful prebuilt classes. For example, you can reuse the C++ standard library’s classes in any program by including the appropriate headers—in this case, the <string> header (line 4). The name string, like the name cout, belongs to namespace std.

C++20 string Member Function length

20 Lines 13–15 output each string and its length. The string class’s length member function (new in C++20) returns the number of characters stored in a particular string object. In line 13, the expression

s1.length()

returns s1’s length by calling the object’s length member function. To call this member function for a specific object, you specify the object’s name (s1), followed by the dot operator (.), then the member function name (length) and a set of parentheses. Empty paren-theses indicate that length does not require any additional information to perform its task. Soon, you’ll see that some member functions require additional information called arguments to perform their tasks.

From main’s view, when the length member function is called:

1. The program transfers execution from the call (line 13 in main) to member function length. Because length was called via the s1 object, length “knows” which object’s data to manipulate.

2. Next, member function length performs its task—that is, it returns s1’s length to line 13 where the function was called. The main function does not know the details of how length performs its task, just as the driver of a car doesn’t know the details of how engines, transmissions, steering mechanisms and brakes are implemented.

3. The cout object displays the number of characters returned by member function length, then the program continues executing, displaying the strings s2 and s3 and their lengths.

Comparing string Objects with the Equality Operators

Like numbers, strings can be compared with one another. Lines 18–20 show the results of comparing s2 to s1 using the equality operators—string comparisons are case sensitive.4

4. In Chapter 8, you’ll see that strings perform lexicographical comparisons using the numerical values of the characters in each string.

Normally, when you output a condition’s value, C++ displays 0 for false or 1 for true. The stream manipulator boolalpha (line 18) from the <iostream> header tells the output stream to display condition values as the words false or true.

string Member Function empty

Line 25 calls string member function empty, which returns true if the string is empty; otherwise, it returns false. The object s3 was initialized by default to the empty string, so it is indeed empty, and the body of the if statement will execute.

string Concatenation and Assignment

Line 27 assigns a new value to s3 produced by “adding” the strings s1 and s2 using the + operator—this is known as string concatenation. After the assignment, s3 contains the characters of s1 followed by the characters of s2. Line 28 outputs s3 to demonstrate that the assignment worked correctly.

C++20 string Member Functions starts_with and ends_with

20 Lines 32–35 demonstrate new string member functions starts_with and ends_with, which return true if the string starts with or ends with a specified substring, respectively; otherwise, they return false. Lines 32 and 33 show that s1 starts with "ha", but s2 does not. Lines 34 and 35 show that s1 does not end with "ay" but s2 does.

2.8 Wrap-Up

We presented many important basic features of C++ in this chapter, including displaying data on the screen, inputting data from the keyboard and declaring variables of fundamental types. In particular, you learned to use the output stream object cout and the input stream object cin to build simple interactive programs. We declared and initialized variables and used arithmetic operators to perform calculations. We discussed the order in which C++ applies operators (i.e., the rules of operator precedence), as well as the grouping of the operators. You saw how C++’s if statement allows a program to make decisions. We introduced the equality and relational operators, which we used to form conditions in if statements.

Finally, we introduced the notion of “objects natural” learning by creating objects of the C++ standard library class string and interacting with them using equality operators and string member functions. In subsequent chapters, you’ll create and use many objects of existing classes to accomplish significant tasks with minimal amounts of code. Then, in Chapters 1014, you’ll create your own custom classes. You’ll see that C++ enables you to “craft valuable classes.” In the next chapter, we begin our introduction to control statements, which specify the order in which a program’s actions are performed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset