Objectoriented Programming Using C Fourth Edition 4th Joyce Farrell
Objectoriented Programming Using C Fourth Edition 4th Joyce Farrell
Objectoriented Programming Using C Fourth Edition 4th Joyce Farrell
Objectoriented Programming Using C Fourth Edition 4th Joyce Farrell
1. Objectoriented Programming Using C Fourth
Edition 4th Joyce Farrell download
https://ebookbell.com/product/objectoriented-programming-using-c-
fourth-edition-4th-joyce-farrell-2434900
Explore and download more ebooks at ebookbell.com
2. Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Object Oriented Programming Using C Simon Kendal
https://ebookbell.com/product/object-oriented-programming-using-c-
simon-kendal-43272996
Object Oriented Programming Using C Simon Kendal
https://ebookbell.com/product/object-oriented-programming-using-c-
simon-kendal-10893738
Objectoriented Programming Using C And Java Anand Vasappanavara Gautam
Vasappanavara Ramesh Vasappanavara Anand Vasappanavara
https://ebookbell.com/product/objectoriented-programming-using-c-and-
java-anand-vasappanavara-gautam-vasappanavara-ramesh-vasappanavara-
anand-vasappanavara-7261816
Handson Objectoriented Programming With C Build Maintainable Software
With Reusable Code Using C Raihan Taher
https://ebookbell.com/product/handson-objectoriented-programming-with-
c-build-maintainable-software-with-reusable-code-using-c-raihan-
taher-24071958
3. Realworld Implementation Of C Design Patterns Overcome Daily
Programming Challenges Using Elements Of Reusable Objectoriented
Software 1st Edition Bruce M Van Horn Ii
https://ebookbell.com/product/realworld-implementation-of-c-design-
patterns-overcome-daily-programming-challenges-using-elements-of-
reusable-objectoriented-software-1st-edition-bruce-m-van-horn-
ii-46570982
Realworld Implementation Of C Design Patterns Overcome Daily
Programming Challenges Using Elements Of Reusable Objectoriented
Software Bruce M Van Horn Ii
https://ebookbell.com/product/realworld-implementation-of-c-design-
patterns-overcome-daily-programming-challenges-using-elements-of-
reusable-objectoriented-software-bruce-m-van-horn-ii-56447252
Object Oriented Programming Using Java Kendal Simon
https://ebookbell.com/product/object-oriented-programming-using-java-
kendal-simon-5395572
Object Oriented Programming Using Java As Per Ce Cse It And Ict Be 5th
Semester Syllabus Of Gtu Chirag Patel
https://ebookbell.com/product/object-oriented-programming-using-java-
as-per-ce-cse-it-and-ict-be-5th-semester-syllabus-of-gtu-chirag-
patel-231665142
Beginning Object Oriented Programming Using Visual Basic 2005 From
Novie To Professiona Dan Clark
https://ebookbell.com/product/beginning-object-oriented-programming-
using-visual-basic-2005-from-novie-to-professiona-dan-clark-4112518
8. BRIEF CONTENTS
PREFACE xvii
READ THIS BEFORE YOU BEGIN xxi
CHAPTER 1 AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING
AND C++ 1
CHAPTER 2 EVALUATING C++ EXPRESSIONS 51
CHAPTER 3 MAKING DECISIONS 81
CHAPTER 4 PERFORMING LOOPS 123
CHAPTER 5 UNDERSTANDING ARRAYS, STRINGS, AND POINTERS 165
CHAPTER 6 USING C++ FUNCTIONS 223
CHAPTER 7 USING CLASSES 283
CHAPTER 8 CLASS FEATURES AND DESIGN ISSUES 333
CHAPTER 9 UNDERSTANDING FRIENDS AND OVERLOADING OPERATORS 385
CHAPTER 10 UNDERSTANDING INHERITANCE 451
CHAPTER 11 USING TEMPLATES 501
CHAPTER 12 HANDLING EXCEPTIONS 557
CHAPTER 13 ADVANCED INPUT AND OUTPUT 615
CHAPTER 14 ADVANCED TOPICS 673
APPENDIX A GETTING STARTED WITH MICROSOFT VISUAL STUDIO 2008 731
APPENDIX B GETTING STARTED WITH OTHER C++ COMPILERS 737
APPENDIX C OPERATOR PRECEDENCE AND ASSOCIATIVITY 745
APPENDIX D FORMATTING OUTPUT 749
APPENDIX E GENERATING RANDOM NUMBERS 755
GLOSSARY 761
INDEX 777
iii
10. CONTENTS
PREFACE xvii
READ THIS BEFORE YOU BEGIN xxi
CHAPTER 1 AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING
AND C++ 1
THE TASK OF PROGRAMMING 2
PROGRAMMING UNIVERSALS 3
PROCEDURAL PROGRAMMING 5
Early Procedural Programs 5
Modularity and Abstraction 7
Encapsulation 10
OBJECT-ORIENTED PROGRAMMING 11
Objects and Classes 11
Inheritance 12
Polymorphism 13
GETTING STARTED IN THE C++ PROGRAMMING ENVIRONMENT 13
Creating a main()Function 14
WORKING WITH VARIABLES AND THE const QUALIFIER 16
The int Data Type 18
The char Data Type 18
The bool Data Type 19
Floating-Point Data Types 19
Declaring Variables 19
The const Qualifier 21
CREATING COMMENTS 22
ANSI/ISO STANDARD C++ 23
Using Libraries, Preprocessor Directives, and namespace 24
PRODUCING C++ OUTPUT 25
PROVIDING C++ INPUT 27
A FIRST LOOK AT DATA STRUCTURES AND CLASSES 29
YOU DO IT 32
Creating a Program That Displays Variable Values 32
Introducing Errors into a Program 34
Modifying a Program to Accept Input Values 35
Creating a Simple Structure 36
v
11. C O N T E N T S
CHAPTER SUMMARY 37
KEY TERMS 38
REVIEW QUESTIONS 43
EXERCISES 45
CASE PROJECT 1 48
CASE PROJECT 2 48
UP FOR DISCUSSION 49
CHAPTER 2 EVALUATING C++ EXPRESSIONS 51
USING C++ BINARY ARITHMETIC OPERATORS 52
Using Modulus 56
PRECEDENCE AND ASSOCIATIVITY OF ARITHMETIC OPERATIONS 58
SHORTCUT ARITHMETIC OPERATORS 59
Compound Assignment Operators 59
Increment and Decrement Operators 60
OTHER UNARY OPERATORS 61
EVALUATING BOOLEAN EXPRESSIONS 63
PERFORMING OPERATIONS ON STRUCT FIELDS 65
YOU DO IT 67
Using Arithmetic Operators 67
Using Prefix and Postfix Increment and Decrement Operators 68
Using Operators with struct Fields 69
CHAPTER SUMMARY 71
KEY TERMS 71
REVIEW QUESTIONS 73
EXERCISES 75
CASE PROJECT 1 78
CASE PROJECT 2 78
UP FOR DISCUSSION 79
CHAPTER 3 MAKING DECISIONS 81
USING THE IF STATEMENT 82
The Single-Alternative if 82
The Dual-Alternative if 85
USING A NESTED IF 87
AVOIDING COMMON PITFALLS WITH IF STATEMENTS 89
Pitfall: Forgetting that C++ Comparisons are Case Sensitive 89
Pitfalls: Assuming that indentation has a logical purpose, adding
an Unwanted Semicolon, and Forgetting Curly Braces 90
vi
12. C O N T E N T S
Pitfall: Using = Instead of == 91
Pitfall: Making Unnecessary Comparisons 93
Pitfall: Creating Unreachable Code 94
USING THE SWITCH STATEMENT 96
USING THE CONDITIONAL OPERATOR 99
USING THE LOGICAL AND AND OR OPERATORS 100
Using the Logical AND Operator 100
Using the Logical OR Operator 102
Pitfall: Using OR When You Mean AND 104
Combining AND and OR Selections 104
MAKING DECISIONS WITH STRUCTURE FIELDS 105
YOU DO IT 107
Using a Single-Alternative if 107
Using a Dual-Alternative if 108
Using a Compound Condition and Nested ifs 109
CHAPTER SUMMARY 111
KEY TERMS 112
REVIEW QUESTIONS 113
EXERCISES 117
CASE PROJECT 1 121
CASE PROJECT 2 121
UP FOR DISCUSSION 122
CHAPTER 4 PERFORMING LOOPS 123
THE while LOOP 124
WRITING TYPICAL LOOPS 127
A Typical Loop: Input Verification 127
A Typical Loop: Reading Input Records 128
AVOIDING COMMON PITFALLS WITH LOOPS 130
Pitfall: Adding an Unwanted Semicolon 131
Pitfalls: Forgetting Curly Braces or Forgetting to Alter a Loop Control Variable 132
Pitfall: Failing to Initialize a Loop Control Variable 133
ACCUMULATING TOTALS 135
THE FOR LOOP 136
PRETEST VS. POSTTEST LOOPS 139
NESTED LOOPS 143
USING LOOPS WITH STRUCTURE FIELDS 145
YOU DO IT 149
Using a Loop to Validate User Data Entry 149
Using a Structure in an Application Containing Several Loops 150
vii
13. C O N T E N T S
CHAPTER SUMMARY 154
KEY TERMS 155
REVIEW QUESTIONS 155
EXERCISES 159
CASE PROJECT 1 161
CASE PROJECT 2 162
UP FOR DISCUSSION 163
CHAPTER 5 UNDERSTANDING ARRAYS, STRINGS, AND POINTERS 165
UNDERSTANDING MEMORY ADDRESSES 166
UNDERSTANDING ARRAYS 167
STORING VALUES IN AN ARRAY 170
ACCESSING AND USING ARRAY VALUES 172
AVOIDING COMMON ARRAY ERRORS 175
Pitfall: Forgetting that Arrays are Zero-Based 175
Pitfall: Accessing Locations Beyond the Array 176
USING PART OF AN ARRAY 177
USING PARALLEL ARRAYS 180
CREATING ARRAYS OF STRUCTURE OBJECTS 183
USING TWO-DIMENSIONAL ARRAYS 185
USING CHARACTER ARRAY STRINGS 188
Strings Created as Arrays of Characters 189
Special String-Handling Problems When Using
Character Arrays 190
AN INTRODUCTION TO THE STRING CLASS 197
USING POINTERS 200
USING A POINTER INSTEAD OF AN ARRAY NAME 201
YOU DO IT 205
Using an Array 205
Understanding Memory Addresses 208
CHAPTER SUMMARY 210
KEY TERMS 211
REVIEW QUESTIONS 212
EXERCISES 215
CASE PROJECT 1 220
CASE PROJECT 2 220
UP FOR DISCUSSION 221
viii
14. C O N T E N T S
CHAPTER 6 USING C++ FUNCTIONS 223
WRITING SIMPLE FUNCTIONS 224
PLACING FUNCTIONS WITHIN FILES 226
Placing a Function as Part of the Same File, Before main() 226
Placing a Function as Part of the Same File, After main() 228
Placing a Function in Its Own File 230
UNDERSTANDING PROCEDURAL ABSTRACTION 232
UNDERSTANDING SCOPE 234
Distinguishing Between Local and Global Variables 234
Using the Scope Resolution Operator 237
RETURNING VALUES FROM FUNCTIONS 239
PASSING VALUES TO FUNCTIONS 243
AVOIDING COMMON ERRORS WHEN USING FUNCTIONS 246
Pitfall: Neglecting to Make Sure the Function Declaration, Header, and Call Agree 246
Pitfall: Indicating an Argument Type in a Function Call 247
Pitfall: Indicating a Return Type in a Function Call 247
Pitfall: Ignoring the Order of Parameters 247
Pitfall: Assuming that an Unused Return Value Has an Effect 248
USING OBJECTS AS PARAMETERS TO,
AND AS RETURN TYPES OF, FUNCTIONS 248
PASSING ADDRESSES TO FUNCTIONS 250
USING REFERENCE VARIABLES WITH FUNCTIONS 253
Declaring Reference Variables 253
Passing Variable Addresses to Reference Variables 255
PASSING ARRAYS TO FUNCTIONS 258
USING INLINE FUNCTIONS 260
USING DEFAULT PARAMETERS 262
OVERLOADING FUNCTIONS 264
Avoiding Ambiguity 266
YOU DO IT 267
Writing Functions That Return Values 267
Writing a Function That Requires a Parameter 269
CHAPTER SUMMARY 270
KEY TERMS 271
REVIEW QUESTIONS 273
EXERCISES 276
CASE PROJECT 1 281
CASE PROJECT 2 281
UP FOR DISCUSSION 282
ix
15. C O N T E N T S
CHAPTER 7 USING CLASSES 283
CREATING CLASSES 284
ENCAPSULATING CLASS COMPONENTS 286
Designing Classes 287
IMPLEMENTING FUNCTIONS IN A CLASS 289
Using Public Functions to Alter Private Data 290
UNUSUAL USE: USING PRIVATE FUNCTIONS AND PUBLIC DATA 295
CONSIDERING SCOPE WHEN DEFINING MEMBER FUNCTIONS 298
USING STATIC CLASS MEMBERS 301
Defining Static Data Members 301
Using Static Functions 305
UNDERSTANDING THE THIS POINTER 307
Using the this Pointer Explicitly 311
Using the Pointer-to-Member Operator 311
UNDERSTANDING POLYMORPHISM 313
YOU DO IT 314
Creating and Using a Class 314
Using a static Field 317
Understanding How static and Non-static Fields are Stored 320
CHAPTER SUMMARY 321
KEY TERMS 322
REVIEW QUESTIONS 323
EXERCISES 327
CASE PROJECT 1 330
CASE PROJECT 2 331
UP FOR DISCUSSION 331
CHAPTER 8 CLASS FEATURES AND DESIGN ISSUES 333
CLASSIFYING THE ROLES OF MEMBER FUNCTIONS 334
UNDERSTANDING CONSTRUCTORS 335
WRITING CONSTRUCTORS WITHOUT PARAMETERS 336
WRITING CONSTRUCTORS WITH PARAMETERS 341
Pitfall: Using Parentheses When Instantiating an Object with a Default Constructor 344
OVERLOADING CONSTRUCTORS 345
USING DESTRUCTORS 347
UNDERSTANDING COMPOSITION 352
Using Composition When Member Classes Contain Non-default Constructors 355
USING #IFNDEF, #DEFINE, AND #ENDIF 358
IMPROVING CLASSES 361
x
16. C O N T E N T S
Selecting Member Data and Function Names 361
Reducing Coupling Between Functions 363
Increasing Cohesion in a Function 363
YOU DO IT 365
Creating a Class with a Constructor 365
Using Constructor Parameters 368
Understanding Composition 369
CHAPTER SUMMARY 372
KEY TERMS 374
REVIEW QUESTIONS 375
EXERCISES 378
CASE PROJECT 1 382
CASE PROJECT 2 383
UP FOR DISCUSSION 384
CHAPTER 9 UNDERSTANDING FRIENDS AND OVERLOADING OPERATORS 385
WHAT ARE FRIENDS? 386
HOW TO DECLARE A FUNCTION AS A FRIEND 387
UNDERSTANDING THE BENEFITS OF OVERLOADING AND POLYMORPHISM 391
USING A FRIEND FUNCTION TO ACCESS DATA FROM TWO CLASSES 393
Using a Forward Declaration 395
OVERLOADING OPERATORS—THE GENERAL RULES 397
OVERLOADING AN ARITHMETIC OPERATOR 402
Paying Attention to the Order of the Operands 405
OVERLOADING AN OPERATOR TO WORK WITH
AN OBJECT AND A PRIMITIVE TYPE 406
USING MULTIPLE OPERATIONS IN AN EXPRESSION 409
OVERLOADING OUTPUT 412
OVERLOADING INPUT 416
OVERLOADING THE PREFIX ++ AND – – OPERATORS 418
USING POSTFIX INCREMENT AND DECREMENT OPERATORS 421
OVERLOADING THE == OPERATOR 422
OVERLOADING THE = OPERATOR 424
OVERLOADING [ ] AND ( ) 430
YOU DO IT 434
Overloading an Arithmetic Operator 434
Overloading an Output Operator 435
CHAPTER SUMMARY 436
KEY TERMS 438
xi
17. C O N T E N T S
REVIEW QUESTIONS 439
EXERCISES 442
CASE PROJECT 1 447
CASE PROJECT 2 448
UP FOR DISCUSSION 449
CHAPTER 10 UNDERSTANDING INHERITANCE 451
UNDERSTANDING INHERITANCE 452
UNDERSTANDING THE ADVANTAGES PROVIDED BY INHERITANCE 453
CREATING A DERIVED CLASS 454
UNDERSTANDING INHERITANCE RESTRICTIONS 458
CHOOSING THE CLASS ACCESS SPECIFIER 462
OVERRIDING INHERITED ACCESS 463
OVERRIDING AND OVERLOADING PARENT CLASS FUNCTIONS 467
PROVIDING FOR BASE CLASS CONSTRUCTION 474
USING MULTIPLE INHERITANCE 478
DISADVANTAGES OF USING MULTIPLE INHERITANCE 481
USING VIRTUAL BASE CLASSES 482
YOU DO IT 484
Creating a Base Class 484
Creating a Child Class 486
Creating Another Child Class 488
Using Multiple Inheritance 489
CHAPTER SUMMARY 491
KEY TERMS 492
REVIEW QUESTIONS 493
EXERCISES 496
CASE PROJECT 1 498
CASE PROJECT 2 499
UP FOR DISCUSSION 500
CHAPTER 11 USING TEMPLATES 501
UNDERSTANDING THE USEFULNESS OF FUNCTION TEMPLATES 502
CREATING FUNCTION TEMPLATES 504
USING MULTIPLE PARAMETERS IN FUNCTION TEMPLATES 506
OVERLOADING FUNCTION TEMPLATES 509
USING MORE THAN ONE TYPE IN A FUNCTION TEMPLATE 511
USING MORE THAN ONE PARAMETERIZED TYPE IN A FUNCTION TEMPLATE 513
xii
18. C O N T E N T S
EXPLICITLY SPECIFYING THE TYPE IN A FUNCTION TEMPLATE 516
Using Multiple Explicit Types in a Function Template 518
USING CLASS TEMPLATES 519
CREATING A COMPLETE CLASS TEMPLATE 521
UNDERSTANDING THE USEFULNESS OF CONTAINER CLASSES 523
CREATING AN ARRAY TEMPLATE CLASS 525
INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY 531
Inserting a New Element into a Vector Using Iterators and the insert()Method 536
Sorting Vector Elements Using the sort()Algorithm 536
YOU DO IT 540
Creating a Function Template 540
Proving the Template Function Works with Class Objects 541
CHAPTER SUMMARY 544
KEY TERMS 546
REVIEW QUESTIONS 547
EXERCISES 550
CASE PROJECT 1 553
CASE PROJECT 2 554
UP FOR DISCUSSION 555
CHAPTER 12 HANDLING EXCEPTIONS 557
UNDERSTANDING THE LIMITATIONS OF TRADITIONAL ERROR HANDLING METHODS 558
THROWING EXCEPTIONS 560
USING TRY BLOCKS 563
CATCHING EXCEPTIONS 564
USING MULTIPLE THROW STATEMENTS AND MULTIPLE CATCH BLOCKS 566
Determining the Order of catch Blocks 568
USING THE DEFAULT EXCEPTION HANDLER 569
UNDERSTANDING EXCEPTION CLASSES IN THE STANDARD RUNTIME LIBRARY 570
An Example of an Automatically Thrown logic_error 571
Using the what()Function 573
Explicitly Throwing a Built-in exception 573
DERIVING YOUR OWN EXCEPTIONS FROM THE EXCEPTION CLASS 576
Overriding the Exception Class what()Function 580
USING EXCEPTION SPECIFICATIONS 582
Exception Specifications in ANSI C++ 582
How Visual C++ Departs from the ANSI Standard 583
UNWINDING THE STACK 583
RETHROWING EXCEPTIONS 589
xiii
19. C O N T E N T S
HANDLING MEMORY ALLOCATION EXCEPTIONS 591
WHEN TO USE EXCEPTION HANDLING 593
YOU DO IT 594
Creating a Typical Data Entry Application 594
Modifying the SimpleDataEntry Program to Throw an Exception 595
Creating a Custom Exception Class 597
Throwing and Catching Multiple Exceptions 599
Using a Generic catch Block 602
CHAPTER SUMMARY 603
KEY TERMS 605
REVIEW QUESTIONS 606
EXERCISES 609
CASE PROJECT 1 613
CASE PROJECT 2 613
UP FOR DISCUSSION 614
CHAPTER 13 ADVANCED INPUT AND OUTPUT 615
UNDERSTANDING CIN AND COUT AS OBJECTS 616
USING ISTREAM MEMBER FUNCTIONS 618
Using the get()Function 618
Using the ignore()Function 621
Using the getline()Function 623
Other istream Member Functions 624
USING OSTREAM MEMBER FUNCTIONS 625
Using Format Flags with setf()and unsetf() 625
Using the width()Function 626
Using the precision()Function 627
Other ostream Member Functions 627
USING MANIPULATORS 628
Using the setprecision()Manipulator 629
Using the setw()Manipulator 630
Using the setiosflags()and resetiosflags()Manipulators 631
Using the oct, hex, and showbase manipulators 631
CREATING MANIPULATOR FUNCTIONS 632
UNDERSTANDING COMPUTER FILES 634
SIMPLE FILE OUTPUT 636
SIMPLE FILE INPUT 642
WRITING AND READING OBJECTS 644
WORKING WITH RANDOM ACCESS FILES 648
Setting up a File for Direct Access 650
xiv
20. C O N T E N T S
xv
Writing Records to a File Randomly 652
Randomly Reading the File 653
YOU DO IT 655
Using stream Functions and Manipulators 655
Creating a Manipulator 657
Writing to and Reading from a File 658
CHAPTER SUMMARY 660
KEY TERMS 662
REVIEW QUESTIONS 664
EXERCISES 667
CASE PROJECT 1 669
CASE PROJECT 2 670
UP FOR DISCUSSION 671
CHAPTER 14 ADVANCED TOPICS 673
USING ENUMERATIONS 674
UNDERSTANDING THE BINARY SYSTEM 676
UNDERSTANDING WHY COMPUTERS USE THE BINARY SYSTEM 679
USING INDIVIDUAL BITS TO STORE DATA 681
CONVERTING A GROUP OF BIT FIELDS TO AN INTEGER VALUE 684
USING THE BITWISE AND OPERATOR WITH A MASK 691
USING THE BITWISE INCLUSIVE OR OPERATOR 696
SHIFTING BITS 702
UNDERSTANDING RECURSION 704
USING A RECURSIVE FUNCTION TO SORT A LIST 708
YOU DO IT 712
Working with an Enumeration 712
Working with Bits 713
Using a Multi-Bit Field 715
Using a Mask to Convert Letters from Lowercase
to Uppercase 716
Working with Recursion 717
CHAPTER SUMMARY 719
KEY TERMS 720
REVIEW QUESTIONS 721
EXERCISES 724
CASE PROJECT 1 728
CASE PROJECT 2 728
UP FOR DISCUSSION 729
21. C O N T E N T S
APPENDIX A GETTING STARTED WITH MICROSOFT VISUAL STUDIO 2008 731
APPENDIX B GETTING STARTED WITH OTHER C++ COMPILERS 737
APPENDIX C OPERATOR PRECEDENCE AND ASSOCIATIVITY 745
APPENDIX D FORMATTING OUTPUT 749
APPENDIX E GENERATING RANDOM NUMBERS 755
GLOSSARY 761
INDEX 777
xvi
22. PREFACE
Object-Oriented Programming Using C++, Fourth Edition is designed for many levels of programming stu-
dents and a variety of programming teaching styles. Readers who are new to programming will find the
basics of programming logic and the C++ programming language covered thoroughly and clearly.
Comprehensive, engaging explanations, multiple programming examples, and step-by-step programming
lessons provide beginning readers with a solid C++ background. Users who know some C++ syntax, but are
new to object-oriented programming, will find objects explored thoroughly from the first chapters. Objects
are introduced early, so those who want to learn objects at the start of their programming experience can
do so. Users who want to postpone objects can simply omit the later sections of each chapter and cover the
basic programming structures with simple data types before returning to the more complex objects later on.
ORGANIZATION AND COVERAGE
Object-Oriented Programming Using C++ contains 14 chapters and five appendices that present clear text
explanations, directed hands-on instruction, and a wealth of exercises. In these chapters, readers learn
about programming logic in general, C++ syntax in particular, and gain an appreciation for and under-
standing of the object-oriented approach. When readers complete the book, they will have an under-
standing of object-oriented concepts as they apply to programming, and the ability to use these concepts
to develop C++ programs.
Chapter 1 provides an overview of programming in general and C++ in particular. You work with vari-
ables, comments, input and output, and data structures. This book distinguishes itself from other C++
books by introducing structure objects in Chapter 1 so that students start thinking in an object-oriented
manner from the beginning of the course.
Chapter 2 focuses on evaluating C++ expressions. Chapters 3, 4, and 5 discuss decisions, loops, arrays,
strings, and pointers—all fundamental building blocks of C++ programs. Chapter 6 provides a solid foun-
dation in writing and using functions including passing parameters by value and by reference and return-
ing values from functions.
Once students understand C++ basics they are ready for Chapters 7 and 8, which delve more completely
into the object-oriented aspects of C++, featuring classes, objects, and design issues. Friend functions and
operator overloading are covered in Chapter 9, and inheritance, another important OO feature, is explained
in Chapter 10.
Advanced C++ features such as templates, exception handling, and advanced input and output techniques,
including writing objects to files, are covered in Chapters 11, 12, and 13. Chapter 14 presents some inter-
esting adjuncts to C++ that make it such a powerful language, including creating enumerations, working
with bits, and understanding recursion.
Five appendices offer further explanation to topics mentioned in the chapters. Appendices A and B describe
how to get started with various C++ compilers. Appendix C contains a handy table of precedence and
associativity. Appendix D contains information on formatting output, and Appendix E is a lesson in
generating random numbers—an important skill in creating scientific simulations and games.
xvii
23. P R E F A C E
APPROACH
Object-Oriented Programming Using C++ teaches object-oriented concepts using C++ as a tool to demonstrate
these concepts. This book teaches programming concepts using a task-driven rather than a command-driven
approach. Structures are introduced in Chapter 1 so that students start thinking about objects right from
the start. However, discussion of objects is reserved for the last sections of the first six chapters, so that
instructors who prefer to start with a procedural approach can omit these sections at first, then go back
to cover them after the first six chapters have been completed.
FEATURES
Object-Oriented Programming Using C++ is an exceptional textbook because it also includes the following
features:
» Objectives. A brief list of objectives appears at the beginning of each chapter so the student has an
overview of the main topics to be covered.
» Notes. These provide additional information about a procedure or topic, such as an alternative method
of performing a procedure.
» Figures. Each chapter averages over 35 figures that contain diagrams, code, working programs, or
screen shots of the programs’ execution.
» Color. Besides adding visual interest to the text, the new two-color design is used to highlight C++
keywords each time they appear in a figure.
» Don’t Do It Icon. It is sometimes illustrative to show an example of how NOT to do something—for
example, having a dead code path in a program. However, students do not always read carefully and
sometimes use logic similar to that shown in what is intended to be a “bad” example. When the
instructor is critical, the frustrated student says, “But that’s how they did it in the book!” Therefore,
although the text will continue to describe bad examples, and the captions for the related figures
will mention that they are bad examples, the book also includes a “Don’t Do It” icon near the offend-
ing section of logic. This icon provides a visual jolt to the student, emphasizing that particular figures
are NOT to be emulated.
» Section Quiz. “Two truths and a lie” appears after each chapter section, with answers provided.
This quiz contains three statements from the preceding section of text—two true and one false. Over
the years, students have requested answers to problems, but we have hesitated to distribute them
in case instructors want to use problems as assignments or test questions. These true-false mini-
quizzes provide students with immediate feedback as they read, without “giving away” answers to
the existing multiple choice and programming problem questions.
» You Do It. After students study each chapter’s concepts, they are invited to create small applications
that illustrate the concepts. Each application is explained step-by-step as the students add appropriate
code to interesting applications.
» Summaries. A summary that recaps the programming concepts and commands covered follows
each chapter.
» Key Terms. Each chapter contains a list of all the key terms defined in the chapter, along with
explanations and presented in the order covered in the chapter. The list of Key Terms serves as an
additional chapter summary.
xviii
NEW!
NEW!
NEW!
24. P R E F A C E
» Review Questions. Each chapter includes 20 multiple choice review questions that test students’
understanding of what they learned in the chapter.
» Programming Exercises. Each chapter contains interesting exercises that provide students with
the opportunity to apply the concepts they have mastered by writing C++ programs.
» Gaming Exercises. In addition to many business-oriented programming exercises at the end of each
chapter, most chapters now also contain at least one game-oriented exercise.
» Debugging Exercises. Each chapter ends with debugging exercises—programs with a few syntax
or logical errors. The student can find the errors and fix them, developing crucial skills of reading
others’ programs, analyzing error messages and probable cause of errors, and solving problems.
» Running Case. The book contains two running cases in which the student develops large classes,
adding appropriate features as each new concept is introduced. By the end of the book, the student
has created two substantial working classes.
» Up For Discussion. Each chapter ends with open-ended, frequently thought-provoking questions
that are appropriate for classroom or online discussion sessions.
» Syntax Improvements. Three minor, but important improvements have been made in the C++ syn-
tax shown throughout the book. First, the main()function of a program always returns 0, consistent
with common business and ANSI standards. Second, spaces have been inserted surrounding all the
insertion and extraction operators, making code easier to read. Third, the asterisks for pointers and
the ampersands for references are shown next to the data type in declarations, with a space follow-
ing. For example : int* ptr;. This makes it clearer that the data type of ptr is int pointer.
» Glossary. All of the Key Terms presented at the end of each chapter are listed in alphabetical order
in a Glossary at the end of the book.
INSTRUCTOR RESOURCES
The following supplemental materials are available when this book is used in a classroom setting. All of
the instructor resources for this book are provided to the instructor on a single CD-ROM.
Electronic Instructor’s Manual. The Instructor’s Manual that accompanies this textbook includes
additional instructional material to assist in class preparation, including suggestions for lecture topics.
ExamView®
. This textbook is accompanied by ExamView, a powerful testing software package that
allows instructors to create and administer printed, computer (LAN-based), and Internet exams.
ExamView includes hundreds of questions that correspond to the topics covered in this text, enabling
students to generate detailed study guides that include page references for further review. The computer-
based and Internet testing components allow students to take exams at their computers, and save the
instructor time by grading each exam automatically.
PowerPoint Presentations. This book comes with Microsoft PowerPoint slides for each chapter. These
slides are included as a teaching aid for classroom presentation; teachers can make them available on the
network for chapter review, or print them for classroom distribution. Instructors can add their own slides
for additional topics they introduce to the class.
Solution Files. Password-protected solutions to all “You Do It” exercises and end-of-chapter exercises
are provided on the Instructor Resources CD-ROM and on the Course Technology Web site at
www.course.com.
xix
NEW!
NEW!
NEW!
25. P R E F A C E
xx
Distance Learning. Course Technology is proud to present online test banks in WebCT and Blackboard
to provide the most complete and dynamic learning experience possible. Instructors are encouraged to
make the most of the course, both online and offline. For more information on how to access the online
test bank, contact your local Course Technology sales representative.
ACKNOWLEDGMENTS
Thank you to all the people who support me while I write and who make this book the best it can be.
Thanks especially to Lisa Ruffolo, my Developmental Editor, who not only edits, but acts as my cheer-
leader, and to Tricia Coia, Managing Editor, who makes every part of the process work together. Thank
also to Amy Jollymore, Acquisitions Editor, who has brought innovation and energy to the publishing
process. Thanks to Erin Dowler, Content Project Manager, and to Deepti Narwat, full service representa-
tive. Thanks to Serge Palladino, Quality Assurance Tester, whose attention to detail has guaranteed that
this is a quality textbook. Thank you to the reviewers who provided helpful and insightful comments
during the development of this book, including Steve Chadwick, Embry-Riddle Aeronautical University;
Robert Dollinger, University of Wisconsin Stevens Point; and Catherine Wyman, DeVry University.
Thank you to my husband Geoff for whom I am more grateful every day.
Finally, this book is dedicated to Rich and Sue in honor of their 30th
wedding anniversary.
26. READ THIS BEFORE
YOU BEGIN
TO THE USER
DATA FILES
To complete some of the steps and exercises in this book, you will need data files that have been created
for this book. Your instructor will provide the data files to you. You also can obtain the files electronically
from the Course Technology Web site by connecting to www.course.com and then searching for this book
by title, author, or ISBN.
Each chapter in this book has its own set of data files, stored in a separate folder. For example, the files
for Chapter 3 are stored in the Chapter03 folder. You can use a computer in your school lab or your own
computer to complete the labs and exercises in this book.
USING YOUR OWN COMPUTER
To use your own computer to complete the steps and exercises in this book, you will need the
following:
» A personal computer. This book was written and quality assurance tested using Microsoft Vista
Professional.
» A C++ compiler. Almost all examples in this book will work with any C++ compiler. This book was
written using Microsoft Visual Studio 2008 Express Edition and quality assurance tested using
Microsoft Visual Studio 2008 Professsional. Appendix A contains instructions on getting started
with Microsoft Visual Studio 2008. Appendix B contains instructions on getting started with some
other compilers and suggests minor modifications you might have to make to your programs to get
them to work correctly using different compilers. If your book came with a copy of Microsoft Visual
Studio 2008 (Express or Professional), then you may install that on your computer and use it to
complete the material.
» Data files. You will not be able to complete the steps and exercises in this book using your own com-
puter unless you have the data files. You can get the data files from your instructor, or you can obtain
the data files electronically from the Course Technology Web site by connecting to www.course.com
and then searching for this book title.
TO THE INSTRUCTOR
To complete the labs and exercises in this book, your students must use a set of data files. These files are
included on the Instructor Resource CD-ROM. They may also be obtained electronically through the
Course Technology Web site at www.course.com. Follow the instructions in the Help file to copy the data
xxi
27. READ THIS BEFORE YOU BEGIN
xxii
files to your server or standalone computer. You can view the Help file using a text editor such as Notepad.
Once the files are copied, you should instruct your users how to copy the files to their own computers
or workstations.
COURSE TECHNOLOGY DATA FILES
You are granted a license to copy the data files to any computer or computer network used by individuals
who have purchased this book.
28. C H A P T E R O N E
AN OVERVIEW OF
OBJECT-ORIENTED
PROGRAMMING AND C++
1
1
»
In this chapter, you will:
Learn about the task of programming
Examine programming universals
Explore procedural programming
Be introduced to object-oriented programming
Get started in the C++ programming environment
Work with variables and the const qualifier
Create comments
Examine the differences between ANSI/ISO C++ and
Standard C++
Produce C++ output with cout
Provide input with cin
Begin to work with data structures and classes
29. AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING AND C++
2
Whether you are new to programming or have already had a class in logic or a programming
language other than C++, this chapter introduces you to the fundamental concepts of pro-
gramming, including procedural and object-oriented programming. After learning or review-
ing what it means to program, you will examine the characteristics of procedural programs
and consider a few examples. Then you will compare procedural and object-oriented
programs and learn the additional features object-orientation provides.
In the rest of the chapter, you will consider the basic principles behind object-oriented pro-
gramming techniques, including objects, classes, inheritance, and polymorphism. Then you
will get started in the C++ programming environment by applying what you have learned. For
example, you will learn how to create a main()function, work with variables and constants,
and create comments. Finally, you will learn how to produce output and process input with
C++, and how to create your first objects.
THE TASK OF PROGRAMMING
Programminga computer involves writing instructions that enable a computer to carry out a single
task or a group of tasks. Writing these sets of instructions, which are known as programs or soft-
ware, requires using a computer programming language and resolving any errors in the instructions
so that the programs work correctly. Programs are also frequently called application programs,
or simply applications, because you apply them to a task such as preparing payroll checks,
creating inventory reports, or—as in the case of game programs—even entertaining someone.
As with any language, learning a computer programminglanguage requires learning both vocab-
ulary and syntax. People speak a variety of languages, such as English and Japanese; similarly, pro-
grammers use many different programming languages, including Java, Visual Basic, C#, and C++.
The rules of any language make up its syntax. Writing in a programming language requires
correct use of that language’s syntax. In English, using incorrect syntax—that is, committing
a syntax error—might make communication more difficult but usually does not prevent it
altogether. If you ask, “Name yours what is?” most people can still figure out what you mean.
If you are vague or spell a word wrong when writing, most people will nevertheless understand
your message. Computers are not nearly as flexible as most people. As a result, using correct
syntax in a computer program is not just important—it’s essential.
Most of today’s programming languages follow syntax rules that are close enough to human
language to make them accessible to anyone willing to learn and practice them. When you
write programs, you write program statements that are instructions that are similar to
English-language sentences. The statements you write in a programming language must be
subsequently translated into machine language. Machine language is the language that com-
puters can understand; it consists of 1s and 0s. A translator program (called either a compiler
or an interpreter) checks your program for syntax errors. If there are no errors, the translator
changes your written program statements into machine language. Therefore, syntax errors
are not a big problem; you always have an opportunity to fix them before you actually attempt
to run the program. For example, if you write a computer program in C++ but spell a word
incorrectly or reverse the required order of two words, the compiler informs you of such
errors and will not let you run the program until you have corrected them.
30. C H A P T E R O N E
3
»NOTE An interpreter is a program that translates programming language instructions one line at a time; a compiler
works by translating the entire program at one time. Usually, you do not choose whether to use a compiler or an interpreter;
instead, the software you use to develop programs in a particular language contains one or the other. C++ is usually thought
of as a compiled language, although interpreter programs are available for it.
Finding logical errors is much more time consuming for a programmer than finding syntax errors.
A logical error occurs when you use a statement that, although syntactically correct, doesn’t do
what you intended. For a program that is supposed to add two numbers and show the sum, logical
errors arise when multiplication is used instead of addition, or when the sum is given before the
arithmetic occurs. The language compiler will not tell you when you have committed a logical
error; only running and testing your program will enable you to find inappropriate statements. You
run a program by issuing a command to execute—that is, to carry out—the program statements.
You test a program by using sample data to determine whether the program results are correct.
»NOTE
Programmers call
some logical errors
semantic errors.
For example, if you
misspell a pro-
gramming lan-
guage word, you
commit a syntax
error, but if you use
a correct word in
the wrong context,
you commit a
semantic error.
»NOTE Selecting data for testing is an art in itself. For example, imagine that you write a program to add two numbers,
and test the program with the values 2 and 2. You cannot be sure that the program is free of logical errors just because the
answer is 4. Perhaps you used the multiplication symbol rather than the addition symbol. You can confirm your program’s
accuracy by testing the program several times using a variety of data.
PROGRAMMING UNIVERSALS
All modern programming languages share common characteristics. For example, all program-
ming languages provide methods for directing output—the information produced by a
program—to a desired object, such as a monitor screen, printer, or file. Similarly, all program-
ming languages provide methods for sending input—the data provided by an outside source,
such as a keyboard, scanner, or file—into computer memory so that a program can manipulate it.
In addition, all programming languages provide a way to name locations in computer memory.
These locations are commonly called variables. For example, if a person asks, “What is yourAge?”
yourAge is considered a variable for two reasons: yourAge has different (varied) values for differ-
ent people, and any person can have a change in the value of yourAge. When writing a computer
program, yourAge becomes the name of a position or location in computer memory; the value
at that location or the state of that location might be 18 or 80, or it might be unknown.
»NOTE
A variable or attrib-
ute is also an
object, although it
is a much simpler
object than a moni-
tor or file.
»TWO TRUTHS AND A LIE: THE TASK OF PROGRAMMING
Two of the following statements are true, and one is false. Identify the false statement and explain why it is false.
1. The grammatical rules of any language make up its logic; violating these rules is a logical error.
2. A translator program (called either a compiler or an interpreter) checks your program for syntax errors and coverts
code to machine language.
3. A logical error occurs when you use a statement that, although syntactically correct, doesn’t do what you intended.
The
false
statement
is
#1.
The
rules
of
any
language
make
up
its
syntax.
Using
statements
in
the
correct
order
at
the
correct
time
are
its
logic.
31. AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING AND C++
When discussing the variable yourAge, the separate words “your” and “Age” are run together
on purpose. All modern programming languages require that variable names be one word;
that is, although they do not have to match any word found in a conventional dictionary, they
cannot include any embedded spaces. Each programming language has other specific rules as
to which characters are not allowed, how many characters may be used in the variable name,
and whether capitalization makes a difference.
4
»NOTE Ideally, variables have meaningful names, although no programming language actually requires that they
meet this standard. A payroll program, for example, is easier to read if a variable that is meant to hold your salary is called
yourSalary, but it is legal—that is, acceptable to the language-translating software—to call the variable ImHungry
or jqxBr.
A variable may have only one value at a time, but it is the ability of memory variables to change
in value that makes computers and programming worthwhile. Because one memory location,
or variable, can be used repeatedly with different values, program instructions can be written
once and then used for thousands of problems. Thus, one set of payroll instructions at your
company might produce thousands of individual paychecks each week, and a variable for
hourly wage, perhaps called hourlyWage, can be reused for each employee, holding a differ-
ent value as each individual employee’s paycheck is calculated.
In many computer programming languages, including C++, variables must be explicitly declared,
that is, given a data type as well as a name, before they can be used. The data type of a variable
defines what kind of values may be stored in a variable and what kind of operations can be per-
formed on it. Most computer languages allow at least two types: one for numbers and one for char-
acters. Numericvariables hold values like 13 or -6. Charactervariables hold values like ‘A’ or ‘&’.
Many languages include even more specialized types, such as integer (for storing whole numbers)
or floating point (for storing numbers with decimal places). Some languages, including C++, also
let you create your own types. The distinction between variable types is important because com-
puters handle the various types of data differently; each type of variable requires a different amount
of storage and answers to different rules for manipulation. When you declare a variable with a
type, you aren’t merely naming it; you are giving it a set of characteristics and allowable values.
»NOTE Numeric values like 13 and -6 are called numeric constants; they always appear without quotes. Character
values like ‘A’ and ‘&’ are character constants and, in C++, always appear within single quotes. Literal values like 13 and
‘A’ are unnamed constants—they do have an identifier. Later in the chapter, you will learn to create named constants.
»TWO TRUTHS AND A LIE: PROGRAMMING UNIVERSALS
1. All programming languages provide methods for directing output to a monitor screen, printer, or file and for sending
input into a computer program so that it can be manipulated.
2. All modern programming languages allow you to declare variables which can have multiple values at the same time.
3. In C++, variables must be given a data type as well as a name before they can be used.
The
false
statement
is
#2.
A
variable
may
have
only
one
value
at
a
time,
but
it
is
the
ability
of
memory
variables
to
change
in
value
that
makes
computers
and
programming
worthwhile.
32. C H A P T E R O N E
PROCEDURAL PROGRAMMING
For most of the history of computer programming, which now covers roughly 60 years, most
programs were written procedurally. Procedural programs consist of a series of steps or pro-
cedures that take place one after the other. The programmer determines the exact conditions
under which a procedure takes place, how often it takes place, and when the program stops.
Programmers write procedural programs in many programming languages, such as COBOL,
BASIC, FORTRAN, and RPG. You can also write procedural programs in C++. Although each
language has a different syntax, they all share many elements.
Over the years, as programmers have sought better ways to accommodate the way people
work best on computers, procedural programming techniques have evolved into object-
oriented techniques. Some older languages do not support object-oriented techniques, but
several newer languages do, including Visual Basic, Java, C#, and C++.
EARLY PROCEDURAL PROGRAMS
When programming languages were first used, the programmer’s job was to break a task into
small, specific steps. Each step was then coded in an appropriate language.
Consider a program that creates customer bills for a small business. Assume that the business
sells only one product that costs exactly $7.99. Each customer order must contain the desired
quantity of the item and the customer’s name and address. If you could write the program in
English rather than in a programming language, a simple version of the program might look
something like Figure 1-1.
5
declare variables quantityOrdered, customerName, customerAddress, and balanceDue
read in quantityOrdered, customerName, and customerAddress from disk
print "From:"
print "ABC Company"
print "Stevens Point, WI"
print "Send To:"
print customerName
print customerAddress
multiply quantityOrdered by 7.99 giving balanceDue
print balanceDue
Figure 1-1 English language version of a simple procedural billing program
The programmer creates every step needed to produce a bill. He or she also chooses unique,
descriptive variable names, such as customerName and balanceDue.
»NOTE In a real-life program used by a business, often called a production program, the data stored in variables
such as customerName and customerAddress would most likely be divided into appropriate subfields. Most
companies would store firstName and lastName in separate fields, but use both on a customer bill. Similarly,
streetAddress, city, state, and zipCode are likely to be separate variables. The example in Figure 1-1 uses
customerName and customerAddress to limit the number of statements.
33. AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING AND C++
Basic logic components used in programs are called control structures. Three basic control
structures are used in procedural programming. In the sequence structure, program steps
execute one after another, without interruption. The order of some of the statements is
important; for example, when producing a bill, you must determine the balanceDue before
you can print it out. For some other statements, however, order is unimportant. In the process
shown in Figure 1-1, you can print the “From:” and “Send To:” information, compute the
balanceDue, and then print the balanceDue, but you can instead compute the balanceDue
first, print the “From:” and “Send To:” information, and then print the balanceDue with no
difference in the resulting bill.
Procedural programs can also include a second control structure called a selection
structure, which you use to perform different tasks based on a condition. Perhaps you give a
$5 discount to any customer who orders more than a dozen of an item. Figure 1-2 shows how
this is accomplished. The selection occurs in the second statement from the bottom of the
program.
6
»NOTE
Programmers also
call a selection
a decision or an
if-then.
declare variables quantityOrdered, customerName, customerAddress, and balanceDue
read in quantityOrdered, customerName, and customerAddress from disk
print "From:"
print "ABC Company"
print "Stevens Point, WI"
print "Send To:"
print customerName
print customerAddress
multiply quantityOrdered by 7.99 giving balanceDue
if quantityOrdered is greater than 12 then
subtract 5 from balanceDue
print balanceDue
Figure 1-2 Adding a selection structure to the simple procedural billing program
In the example shown in Figure 1-2, $5 is deducted from the balanceDue if—and only if—
the customer orders more than 12 items. The actual program that produces bills for a com-
pany might have many more selection statements than this example and is usually far
more detailed. What if you’re out of stock? What about taxes? What if the customer has
a credit balance that should be applied to this order? What if one of the data items like
quantityOrdered or customerAddress has been left blank? Some programs contain
dozens or even hundreds of selection statements.
The third control structure used in computer programs is the loop structure, which repeats
actions while some condition remains unchanged. When companies bill customers, they usu-
ally bill many customers at one time. The relevant program accesses a customer record from
34. C H A P T E R O N E
an input file, produces a bill, and continues to repeat the same steps until no more customers
remain in the file. The example in Figure 1-3 shows a program that loops.
7
declare variables quantityOrdered, customerName, customerAddress, and balanceDue
repeat until there are no more input records on the disk
read in quantityOrdered, customerName, and customerAddress from disk
print "From:"
print "ABC Company"
print "Stevens Point, WI"
print "Send To:"
print customerName
print customerAddress
multiply quantityOrdered by 7.99 giving balanceDue
if quantityOrdered is greater than 12 then
subtract 5 from balanceDue
print balanceDue
Figure 1-3 Adding a loop to a simple procedural billing program
The indentation shown in the code in Figure 1-3 indicates that all 10 statements, from
“read” until “print balanceDue”, occur repeatedly “until there are no more
input records on the disk”.
»NOTE
Some programmers
call the loop struc-
ture a repetition or
iteration structure.
»NOTE In reality, production programmers structure their loops a little differently to avoid printing one useless cus-
tomer bill after the last data record is read from the disk. You will become comfortable with this concept after you learn
about writing C++ loops.
The billing program shown in Figure 1-3 does not contain nearly as many sequential steps,
selections, or loops as a full-blown production program would, but even as it stands, the
billing program contains quite a few statements. As programs grow more complicated, they
can contain many hundreds or even thousands of separate statements, and are difficult to
follow. Luckily, all modern programming languages allow programmers to break their pro-
grams into smaller, easier-to-follow modules.
MODULARITY AND ABSTRACTION
Programming in the oldest procedural languages had two major disadvantages:
» The programming process involved so much detail that the programmer (and any person
reading the program) lost sight of the big picture.
» Similar statements required in various parts of the program had to be rewritten in more
than one place.
Writing programs became easier when programming languages began to allow the programmer
to write methods—groups of statements that can be executed as a unit. Using methods
35. AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING AND C++
allows programmers to group statements together into modules, which are known in various
programming languages as functions, procedures, methods, subprograms, subroutines, or
simply routines. For example, you can create a module named printReturnAddress(), as
shown in the sample code in Figure 1-4. The module name printReturnAddress()is fol-
lowed by a set of empty parentheses for two reasons:
» Using the parentheses helps you identify printReturnAddress()as a module rather
than a variable or other program component.
» You will learn shortly that in C++ (as well as in many other programming languages),
parentheses are used when naming all modules.
8
module printReturnAddress()
print "From:"
print "ABC Company"
print "Stevens Point, WI"
endModule
Figure 1-4 The printReturnAddress()module
»NOTE
In general, C++
programmers use
the term “func-
tions” when refer-
ring to methods.
“Methods” is the
more generic term.
You will learn more
about functions
later in this chapter.
You can then change the customer billing program so it looks like the sample code in Figure 1-5.
The shaded statement executes the entire printReturnAddress()module that performs
the three actions listed in Figure 1-4.
declare variables quantityOrdered, customerName, customerAddress,and balanceDue
repeat until there are no more input records on the disk
read in quantityOrdered, customerName, and customerAddress from disk
printReturnAddress()
print "Send To:"
print customerName
print customerAddress
multiply quantityOrdered by 7.99 giving balanceDue
if quantityOrdered is greater than 12 then subtract 5 from balanceDue
print balanceDue
Figure 1-5 Billing program that uses the printReturnAddress()module
The program that includes the printReturnAddress()module is slightly shorter than the
original program because three separate statements are summarized by a single module
name. The use of the method name in the program represents a call to the method—using
the method’s name to cause execution of the statements within the method.
Modular programs are easier to read than nonmodular ones, because one descriptive group name
represents an entire series of detailed steps. If more modules are created, the main program can
36. C H A P T E R O N E
change as shown in Figure 1-6. The shaded statement that executes the printSendToAddress()
module contains the statements that print “Send To:” as well as print the customerName and the
customerAddress values. The shaded statement that executes the computeBalance()module
contains both the multiplication statement and the discount-determining decision.
9
declare variables quantityOrdered, customerName, customerAddress, and balanceDue
Repeat until there are no more input records on the disk
read in quantityOrdered, customerName, and customerAddress from disk
printReturnAddress()
printSendToAddress()
computeBalance()
print balanceDue
Figure 1-6 The procedural billing program containing several module calls
The new program in Figure 1-6 is more concise and more understandable at first glance; it is
also more abstract. Abstraction is the process of paying attention to important properties
while ignoring details. You employ abstraction in your daily life when you make a to-do list
containing tasks like “grocery shop” and “wash car.” Each of those tasks requires multiple
steps and decisions, but you don’t write down every detail involved in those tasks in your list.
Of course, you must attend to the details at some point, and in modularized programs, the
individual modules must eventually be written in a step-by-step process. However, the main
program can be written by using abstract concepts to represent sets of finer details.
»NOTE Programming in the oldest programming languages—machine language and assembly language—is called
low-level programming because you must deal with the details of how the machine physically works. In contrast, pro-
gramming languages such as COBOL and BASIC are called high-level because the programmer need not worry about
hardware details. Although C++ is a high-level language, it is sometimes referred to as mid-level because it contains fea-
tures that allow you to use it on either a high or a low level.
When you work with real-world objects, you take abstraction for granted. For example, you
talk on the telephone without considering how the signals are transmitted. If you had to
worry about every low-level detail—from how the words are formed in your mouth, to how
the signals are transmitted across the phone lines, to how the phone charges are billed to your
account—you would never complete a call.
Programming in a high-level programming language allows you to take advantage of abstrac-
tion. When you write a command to send output to a printer, you don’t instruct the printer
how to actually function—how to form-feed the paper, dispense ink, and print each character.
Instead, you simply write an instruction such as print balanceDue, and the hardware
operations are carried out automatically. Every programming language contains a print (or
similar) command that takes care of the low-level printing details. You simply carry abstrac-
tion one step further when you create a command such as printReturnAddress(), which
takes care of the lower-level return-address details.
Besides the advantage of abstraction, modular programs can be written more quickly because
different programmers can be assigned to write different modules. If the program contains four
modules, four programmers can work simultaneously, with each handling one-fourth of the job.
37. AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING AND C++
An additional advantage to modularization is that a well-written module may be called from
multiple places within the same program or from another program. Many applications can
use the module that prints a company’s return address, for example. Whether you are prepar-
ing job estimates, year-end tax returns, or stockholder reports, you need to print the company
name and address; when a well-written module is stored, any application can use it.
ENCAPSULATION
Modules or procedures act somewhat like relatively autonomous mini-programs. Not only
can modular routines contain their own sets of instructions, but most programming lan-
guages allow them to contain their own variables as well. The variables and instructions
within a module are hidden and contained—that is, encapsulated—which helps to make the
module independent of all other modules and therefore reusable.
You can find many real-world examples of encapsulation. When you build a house, you don’t
invent plumbing fixtures and heating systems. Rather, you reuse previously designed and
tested systems. You don’t need to know the fine details of how the systems work; they are
self-contained units you incorporate in your house by plugging them in through some stan-
dard interface, or means of entry, such as an electrical outlet. This type of encapsulation cer-
tainly reduces the time and effort necessary to build a house. Assuming the plumbing fixtures
and heating systems you choose are already in use in other houses, using existing systems also
improves your house’s reliability—that is, dependability and trustworthiness. Besides not
needing to know how your furnace works, if you replace one model with another, you don’t
care if its internal operations differ. The result—a warm house—is what’s important.
Similarly, reusable software saves time and money and enhances reliability. If the
printReturnAddress()routine in Figure 1-6 has been tested before, you can be confident
that it will produce correctly spaced and aligned output. If another programmer creates a
new and improved printReturnAddress()routine, you don’t care how it works as long
as it prints the data correctly.
When you use modules within procedural programs, you are still limited in your programming. You
must know the names of the modules to call, and you can’t reuse those names for other modules
within the same program. If you need a similar but slightly different procedure, you must create a
new module with a different name, and use the new name when you call the similar module. The
group of techniques called object-oriented programming greatly reduces these limitations.
10
»TWO TRUTHS AND A LIE: PROCEDURAL PROGRAMMING
1. You cannot write procedural programs in most modern programming languages, including C++.
2. The basic control structures are sequence, selection, and loop.
3. Modern programming languages allow programmers to break their programs into modules—groups of statements that
can be executed as a unit.
The
false
statement
is
#1.
Procedural
programs
consist
of
a
series
of
steps
or
procedures
that
take
place
one
after
the
other;
you
can
write
procedural
programs
in
C++
and
all
other
modern
programming
languages.
38. C H A P T E R O N E
OBJECT-ORIENTED PROGRAMMING
Object-oriented programs use all the features of procedural programs you just read about:
they contain variables that are operated on by instructions written in sequence, selection,
and loop statements. However, object-oriented programming requires a different way
of thinking and adds several new concepts to programming:
» You analyze the objects with which you are working—both the attributes of those objects
and the tasks that need to be performed with and on those objects.
» You pass messages to objects, requesting the objects to take action.
» The same message works differently (and appropriately) when applied to the various
objects.
» A method can work appropriately with different types of data it receives, without the
need for separate method names.
» Objects can assume or inherit traits of previously created objects, thereby reducing the
time it takes to create new objects.
» Information hiding is more complete than in procedural programs.
The basic principles behind using object-oriented programming techniques involve:
» Objects
» Classes
» Inheritance
» Polymorphism
Each of these principles is complex. As you work through the lessons and exercises in this
text, you will gain mastery of these concepts as they apply to C++. For now, the following
sections provide a brief overview of each concept.
OBJECTS AND CLASSES
It is difficult to discuss objects without mentioning classes; it is equally difficult to discuss
classes without bringing up objects. An object is any thing. A class consists of a category of
things. An object is a specific item that belongs to a class; it is called an instance of a class. A
class defines the characteristics of its objects and the methods that can be applied to its objects.
11
»NOTE A variable’s data type (such as floating-point, integer, or character) defines what actions can be performed
with the variable. A class is similar—it is a custom data type for more complex objects and it defines what actions can be
performed with them.
For example, Dish is a class. You know that you can hold a Dish object in your hand, that you
can eat from a Dish, and that you can wash it. Dish objects have attributes like size and color.
They also have methods like fill and wash. myBlueCerealBowl is an object and a member
of—or a specific instance of—the Dish class. This situation is considered an is-a relationship
because you can say, “myBlueCerealBowl is a Dish.” For example, yourBlueCerealBowl
39. AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING AND C++
is another instance of the Dish class, as is myPewterSaladPlate. Because myBlueCerealBowl,
yourBlueCerealBowl, and myPewterSaladPlate are examples of a Dish, they share
characteristics. Each has a size and color; each can be filled and washed.
If I tell you I am buying my grandmother a scarletWindsor, you probably have no way of
organizing its characteristics in your brain. Is it something you eat? Is it a piece of clothing? If
I tell you a scarletWindsor “is a” Dish, you have a beginning frame of reference because of
your knowledge of the Dish class in general. If it “is a” Dish, you assume it has a size and
color and that it can be filled and washed.
Similarly, each button on the toolbar of a word-processing program is an instance of a
Button class, and each button shares some general characteristics that all buttons possess.
Even if you have never used a particular piece of software before, if you are presented with
a screen containing a button, you know how to use it.
In a program used to manage a hotel, thePenthouse and theBridalSuite are specific
instances of HotelRoom. Organizing program components into classes and objects reflects a
natural way of thinking.
INHERITANCE
The concept of using classes provides a useful way to organize objects; it is especially useful
because classes are reusable. That is, you can extend them—they are extensible. You can
create new classes that extend or are descendents of existing classes. The descendent classes
can inherit all the attributes of the original (or parent) class, or they can override inappro-
priate attributes.
Employing inheritance can save a lot of work; when you create a class that inherits from
another, you only need to create the new features. When an automobile company designs a
new car model, it does not build every component from scratch. The car might include a new
feature—for example, some model contained the first air bag—but many of a new car’s fea-
tures are simply modifications of existing features. The manufacturer might create a larger
gas tank or a more comfortable seat, but these new features still possess many of the proper-
ties of their predecessors from older models. Most features of new car models are not even
modified; instead, existing components, such as air filters and windshield wipers, are
included on the new model without any changes. Similarly, you can create powerful com-
puter programs more easily if many of their components are used either “as is” or with slight
modifications. Inheritance does not enable you to write any programs that you could not
write if inheritance did not exist; you could create every part of a program from scratch, but
reusing existing classes and interfaces makes your job easier.
In geometry, a Cube is a descendent of a Square. A Cube has all of a Square’s attributes, plus
one additional characteristic: depth. A Cube, however, has a different method of calculating
totalArea (or volume) than does a Square. A DisposableDish class has all the character-
istics of a Dish, plus some special ones. In business, a PartTimeEmployee contains all the
attributes of an Employee, plus more specialized attributes.
Because object-oriented programming languages allow inheritance, you can build classes that
are extensions of existing classes; you don’t have to start fresh each time you want to create
a class.
12
»NOTE
It is conventional,
but not required, to
begin object names
with a lowercase
letter and to begin
class names with
an uppercase
letter.
40. C H A P T E R O N E
POLYMORPHISM
Programming modules might occasionally need to change the way they operate depending on
the context. Object-oriented programs use polymorphism to carry out the same operation in
a manner customized to the object. Such differentiation is never allowed in languages that
aren’t object oriented.
Without polymorphism, you would have to use a separate module or method name for a method
that multiplies two numbers and one that multiplies three numbers. Without polymorphism, you
would have to create separate module names for a method that cleans aDish object, one that cleans
a Car object, and one that cleans aBaby object. Just as your blender can produce juice regardless of
whether you insert two fruits or three vegetables, using a polymorphic, object-oriented multiplica-
tion function call will produce a correct product whether you send it two integers or three floating-
point numbers. Furthermore, using a polymorphic, object-oriented clean method will operate
correctly and appropriately on aDish, a Car, or a Baby. When you master polymorphism in the real
world, you understand that you use different methods to drive a car, to drive a golf ball, and to
drive home a point. This is how the English language works; you understand words based on
their context. When you master polymorphism in an object-oriented programming language,
you take a big step toward producing objects that function like their real-world counterparts.
13
»NOTE Much slang terminology employs polymorphism. For example, if you hear “Roxanne is a dish,” you under-
stand the context and do not envision that she resembles a cereal bowl. Similarly, if you “dish the dirt” with your friends,
you do not serve potting soil on a plate.
GETTING STARTED IN THE C++
PROGRAMMING ENVIRONMENT
The main work area in any C++ programming environment is the editor. An editor is a sim-
plified version of a word processor in which you type your program statements, or source
code. When you save what you have written on a disk, you typically save C++ source code
files with a filename that has a .cpp extension.
»NOTE After you enter the source code for a program, you must compile the program. When you compile a program,
the code you have written is transformed into machine language—the language that the computer can understand. The
output from the compilation is object code—statements that have been translated into something the computer can use.
»TWO TRUTHS AND A LIE: OBJECT-ORIENTED PROGRAMMING
1. An object is a specific instance of a class; a class defines the characteristics of its objects and the methods that can
be applied to its objects.
2. In object-oriented languages, you can create new classes that extend or are descendents of existing classes.
3. Object-oriented programs use procedural methods to carry out the same operation in a manner customized to the object.
The
false
statement
is
#3.
Object-oriented
programs
use
polymorphism
to
carry
out
the
same
operation
in
a
manner
customized
to
the
object.
41. AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING AND C++
A runnable, or executable, program needs the object code as well as code from any outside
sources (other files) to which it refers. The process of integrating these outside references is
called linking. An executable file contains the same filename as the source code and the
object code, but carries the extension .exe to distinguish it as a program.
When you compile a C++ program, error messages and/or warnings might appear. A C++ pro-
gram with errors will not execute; you must eliminate all error messages before you can run the
program. Error messages notify you of fatal errors—errors that are so severe that they prevent
a program from executing. Although a warning will not prevent a program from executing (a
warning is a non-fatal error), it’s important that you examine every warning closely, as each
probably indicates a problem. For example, if you try to display a variable that does not exist,
C++ will issue an error message such as “Undefined symbol”, and you cannot run the program.
If you attempt to display a variable that exists but has not been assigned a valid value, C++ will
not issue an error message but will issue a warning, such as “Possible use of variable before
definition.” You can run the program, but the variable value that is given will be meaningless.
If you have purposely included statements within a program that produce warning messages, for
example, to experiment with what will happen, then it’s okay to ignore warnings and run your
program. However, in professional production programs, you should eliminate all warnings.
CREATING A main()FUNCTION
C++ programs consist of modules called functions. Every statement within every C++ program
is contained in a function.
Every function consists of two parts: a function header and a function body. The initial line of
code in a C++ function makes up the function header, which always has three parts:
» Return type of the function
» Name of the function
» Types and names of any variables enclosed in parentheses, and which the function receives
A C++ program may contain many functions, but every C++ program contains at least one func-
tion, and that function is called main(). Conventionally, the function header used by many C++
programmers is int main(). Using this header implies that the main()function will return an
integer value to the operating system in which you are running the program. The body of every
function in a C++ program is contained in curly braces. You place statements within the function
body. A C++ statement is a segment of C++ code that performs a task; every complete C++ state-
ment ends with a semicolon. Functions that begin with int must include a return statement.
By convention, main()functions use the statement return 0; to mean “everything went
smoothly and this program ended normally.” Therefore, the simplest program you can write has
the form shown in Figure 1-7.
14
int main()
{
return 0;
}
Figure 1-7 The simplest C++ program
»NOTE
In Figure 1-7, the
words int and
return appear in
green. These words
are C++ keywords;
you will learn more
about them in the
next section of this
chapter.
42. C H A P T E R O N E
Placing the main() header and the pair of braces on three separate lines is a matter of style.
This style, in which the braces in a function each occupy a line of their own and align to the
left, is called the exdented style.
The following program, written on a single line, works as well as one written on three lines:
int main() { return 0; }
Another style places the opening curly brace on the same line as the function header:
int main() {
return 0;
}
Other programmers prefer that the curly braces align but be indented a few spaces, as in the
following:
int main()
{
return 0;
}
The most important style issues are that you observe the style guidelines in the place you
work (or those of your instructor in the classroom), and that you apply the style consistently.
As a matter of style, this book will give int main()a line of its own, and then give each
brace a line of its own, aligned to the left.
The function shown in Figure 1-7 doesn’t actually do anything because it contains no C++
statements other than the return statement. To create a program that does something, you
must place one or more additional C++ statements between the opening and closing braces.
As with the return statement, every complete C++ statement ends with a semicolon.
Frequently, a statement occupies a single line in the editor, but a statement can run across
multiple lines in the editor, and you also can place multiple statements on a line if they are
short enough. Often several statements must be grouped together, as when several statements
must occur in a loop. In such a case, the statements have their own set of opening and closing
braces within the main braces, forming a block. One universal C++ truth is that every C++
program must contain exactly the same number of opening braces as closing braces.
15
»NOTE If the main()function does not pass values to other programs or receive values from outside the program,
then main()receives and returns a void type. (In this context, void simply means nothing; more literally, it means
“empty.”) Many C++ programs begin with the header void main(void) or, for simplicity, void main(). Unlike other
C++ functions, if you do not explicitly state any value to be returned from the main()function, it still returns 0, which
means “everything went smoothly.” You might have a teacher or boss who requests that you do not include a return state-
ment in your main()functions, because the value 0 is returned automatically. However, following a common convention,
this book will include the statement return 0; at the end of every main()function
»NOTE You do not need to understand the terms int, void, or return type to successfully run C++ programs. The
purpose of these components will become apparent when you learn to write your own functions. For now, you can begin
each program with the header int main().
»NOTE
In Chapter 6, you
will learn more
about the return
statement, and you
will return many
different values
from functions.
»NOTE
Don’t block state-
ments unless you
have a reason to
do so. Place state-
ments in a block
within a function
only if they form a
unit whose execu-
tion depends on a
selection or a loop.
43. AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING AND C++
WORKING WITH VARIABLES
AND THE const QUALIFIER
In C++, you must provide a name, also called an identifier, to each variable before you can
use it. The ability to use identifiers is a key feature of all modern programming languages;
without them, you would need to memorize a value’s computer memory address. Just as it is
easier for you to remember that the President of the United States lives in the White House
than it is to remember its street address, it is also easier to remember a descriptive identifier
than it is to remember a memory address.
Identifiers for C++ variables can include letters, numbers, and underscores, but must begin
with a letter or underscore. No spaces or other special characters are allowed within a C++
variable name. Age, lastName, tax_2010, ready2go, salary, Salary, and SALARY are all
valid identifiers. Note that salary, Salary, and SALARY could all be used within the same
C++ function without conflict because C++ is case-sensitive. (However, using multiple identi-
fiers whose only difference is the case of some of the letters would be confusing and is not
recommended.) C++ programmers typically use all lowercase letters for variable names, or
else capitalize only the first letter of each new word (after the first word) in a variable name,
as in lastYearGross.
16
»NOTE It is easy to forget to type the closing curly brace to a function, especially if you have typed many statements
since typing the opening brace. Therefore, many programmers recommend typing the closing curly brace immediately
after you type the opening one. Then you can go back and insert needed statements between them.
»NOTE
Besides variables,
you also provide
identifiers for C++
functions, struc-
tures, and classes.
»NOTE
Keywords are also
called reserved
words.
»NOTE
There is an art to
selecting appropri-
ate and useful
identifiers. In
Chapter 8, you will
learn more about
style issues in C++
programs.
»NOTE Beginning an identifier with a lowercase letter and capitalizing subsequent words within the identifier
is a style known as camel casing. An identifier such as lastName resembles a camel because of the “hump” in
the middle.
Every programming language contains a few vocabulary words, or keywords, that you need
in order to use the language. A C++ keyword cannot be used as a variable name. Common C++
»TWO TRUTHS AND A LIE: GETTING STARTED IN THE C++ PROGRAMMING
ENVIRONMENT
1. A runnable, or executable, program needs the object code as well as code from any outside sources (other files) to
which it refers; the process of integrating these outside references is called linking.
2. A C++ program with errors or warnings will not execute; you must eliminate all error messages before you can run
the program.
3. Every statement within every C++ program is contained in a function; each function has a header and a body.
The
false
statement
is
#2.
A
C++
program
with
errors
will
not
execute;
those
are
fatal
errors.
A
program
with
warnings
will
execute.
However,
it’s
important
that
you
examine
every
warning
closely,
as
each
probably
indicates
a
problem.
44. C H A P T E R O N E
keywords are listed in Table 1-1. Keywords vary for each C++ compiler, so some of the terms
listed in Table 1-1 might not be keywords in your system. However, it is best not to use any of
these terms as variables. That way, your code will be portable to other compilers.
17
and continue if public try
and_eq default inline register typedef
asm delete int reinterpret_cast typeid
auto do long return typename
bitand double mutable short uchar_t
bitor dynamiccast namespace signed union
bool else new sizeof unsigned
break enum not state_cast using
case explicit not_eq static virtual
catch extern operator struct void
char false Or switch volatile
class float or_eq template wchar_t
compl for overload this while
const friend private throw xor
constcast goto protected true xor_eq
Table 1-1 Common C++ keywords
Besides an identifier, each named variable must have a data type. C++ supports three simple
data types: integral, floating point, and enumeration.
»NOTE
As you saw in
Figure 1-7, all C++
keywords will
appear in green in
figures in this book.
»NOTE On some older computer systems, only the first 31 characters of a variable name are actually used. Thus, to
ensure portability, you might choose to limit variable names to 31 characters, or at least make them unique within the first
31 characters.
»NOTE The integral and floating-point data types are discussed in this chapter. You will learn about the enumeration
type in Chapter 14. In addition to the simple data types, C++ supports structured data types and pointers. You will learn
about structured data types later in this chapter, and about pointers in future chapters.
An integral data type is a type that holds an integer—a number (either positive or negative)
without a decimal point. Integral data types include nine categories: char, short, int, long,
bool, unsigned char, unsigned short, unsigned int, and unsigned long. Each of
these categories has a different set of values associated with it as well as a specific number of
bytes of memory it occupies, and you might choose one over the other if limiting memory
usage is important in an application. For example, the amount of memory required by short
45. AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING AND C++
and long might be shorter or longer than that required by an int—it depends on the computer
system. However, the integer types are meant to be relative. Therefore, a short might take
less memory than an int, and a long might take more than an int. (But maybe not! The
amount of memory used depends on your system.)
This book will use only three integral types: int, char, and bool.
18
»NOTE
The standards for
C++ were created
after many compil-
ers were already in
use, so, unlike many
other languages,
the size of data
types differs in dif-
ferent compilers
and machine
architectures.
»NOTE You can declare a variable that is meant to hold a whole number as int, short, long, unsigned int,
unsigned short, or unsigned long. If you use a constant whole-number value, such as 12, in a C++ program, it is
an int by default.
»NOTE You can determine the size of variables in your system with the sizeof()operator. For example, to find out
how much memory an integer uses, you can place the following statement in a program:
cout << "Integer size is " << sizeof(int) << " on this computer";
Output might then be: Integer size is 4 on this computer. Later in this chapter, you will learn the meanings
of cout and <<.
»NOTE When an integer is stored in four bytes, the 32 bits used can form only 4,294,967,296 combinations (2 to the
32nd power); thus, only 4,294,967,296 different integer values can be stored. One bit indicates whether the value is positive
or negative; the other 31 bits can represent values from –2,147,483,648 through +2,147,483,647. Problems arise when a
programmer forgets those limits. If you store a value of 5000000000 (5 billion) in an integer named salary and then print
it out, C++ will not produce an error message but will show 705032704 rather than 5000000000. Because 5,000,000,000 is
larger than 4,294,967,296, C++ misinterprets salary as a negative number.
THE int DATA TYPE
An integer value may be stored in an integer data type variable, declared with the keyword
int. Examples are 4, 15, +5000, and –10. Integers do not include decimal points, and they
cannot be written with commas, dollar signs, or any symbols other than a leading + or –.
(Of course, as in everyday arithmetic, if a + symbol is not used, the integer is assumed to be
positive.) You can also declare an integer variable using short int and long int.
THE char DATA TYPE
A character may be stored in a character data type variable, declared with the keyword
char. (Most programmers pronounce this keyword “care” because it comes from “character”;
others pronounce it “char” [as in “to scorch”] because of the way it is spelled. Others say
“car,” like an automobile.) A char may hold any single symbol in the ASCII character set.
Often it contains a letter of the alphabet, but it could include a space, a digit, a punctuation
mark, an arithmetic symbol, or any other special symbol. In C++, a character value is always
expressed in single quotes, such as ‘A’ or ‘&’.
»NOTE A single character, such as ‘D’, is contained in single quotes. A string value, such as “Donna”, uses double
quotes. A value without any quotes, such as D, is assumed to be a variable, structure, or class. You will learn more about
strings later in this chapter.
46. C H A P T E R O N E
THE bool DATA TYPE
A Boolean data type variable is declared using the bool data type, which has only two
possible values—true or false. When you assign a value to a Boolean variable, you can use
true or false, as in the following examples:
bool isDriverInsured = true;
bool isPremiumPaid = false;
However, when you display the value stored in a Boolean variable, a 0 or 1 displays, for false
and true respectively. You will learn much more about how to use this data type in Chapter 3.
19
»NOTE George Boole was a mathematician who lived from 1815 to 1864. He approached logic more simply than his
predecessors did, by expressing logical selections with common algebraic symbols. He is considered the founder of
“Boolean algebra,” or what some call “mathematical logic,” and Boolean (true/false) expressions are named for him.
»NOTE
Some older compil-
ers do not support
the bool data type.
FLOATING-POINT DATA TYPES
Real numbers, or floating-point numbers, are numbers that include decimal positions, such as
98.6, 1000.0002, and –3.85. They may be stored in variables with types float, double, and long
double. The amount of storage required for each of these types varies from computer to com-
puter. Usually a double occupies more memory space than a float (allowing a double to
provide more decimal places, which is called providing greater precision, or accuracy). The max-
imum number of decimal places allowed in a float is usually 6 or 7, and the maximum in a
double is usually 15. This book uses the double data type to manipulate floating-point numbers.
»NOTE When you use different compilers, the amount of storage allocated for different data types can differ. For
example, on many newer compilers, long double and double are the same. A double never takes less storage space
than a float, and a double never takes more space than a long double.
»NOTE
Values that are
floats are called
single-precision
numbers, and
double values are
called double-
precision numbers.
»NOTE
You can declare a
variable that is
meant to hold a
floating-point
number as float
or double. If you
use a floating-point
number constant
value, such as
12.25, in a C++ pro-
gram, it is a double
by default.
DECLARING VARIABLES
Before you can use a variable within any C++ method, you must declare it—that is, provide it
with both a data type and an identifier. A variable declaration is a C++ statement, so it must
end with a semicolon. For example, int myTestScore; is a complete C++ statement that
declares an integer variable named myTestScore. Remember, C++ allows any one-word
identifier that is not a reserved keyword to be used as a variable name, but your programs will
be clearer and your work will be considered more professional if you use descriptive names
like myTestScore instead of cryptic variable names such as mytstscr.
If you write a function that contains variables of diverse types, each variable must be declared
in a statement of its own. If you want to declare two or more variables of the same type, you
may declare them in the same statement, separated by commas. A declaration statement may
include only one data type; you must declare variables of different types in separate statements.
Variables may be declared anywhere in a C++ program, but cannot be used until after they are
declared. Commonly, variables are declared at the beginning of a function, just after the
47. AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING AND C++
opening curly braces. This traditional format makes the variables easier to locate when read-
ing the function later. The code following this paragraph shows the beginning of a typical C++
program that will use variables of several types.
int main()
{
int myAge;
int yourAge;
char myMiddleInitial;
double myMoney, yourMoney;
// More statements usually would belong here
return 0;
}
20
»NOTE
The line that starts
with two forward
slashes (//) in this
example is a pro-
gram comment. You
will learn about
comments in the
next section.
»NOTE In the C programming language, which was a predecessor to C++, all variables had to be declared within
a function before any executable statements could be included. Although C++ does not require this rigid format, many
programmers still think it is good form to declare all variables at the beginning of every function.
Notice that the integer variables myAge and yourAge are each declared in a separate
statement. On the other hand, the two double variables, myMoney and yourMoney, are
declared in the same statement. When you declare two variables within the same state-
ment, you separate the variable names with a comma and place the semicolon at the end
of the list of all the variables of that type. Either style of variable declaration (separate
statements or a shared statement) is acceptable when you declare multiple variables of
the same type.
As a matter of style, some programmers prefer always to declare each variable in its own
statement. This makes it easier to remove a single variable if it is no longer needed. Others
prefer a style in which variables of the same type are declared in the same statement but each
is listed in a separate line, as in the following example:
int myAge,
yourAge,
hisAge;
These three variables are declared in a single statement—notice no semicolon appears until
the end of the last line. By using separate lines, it is easier to see each variable, and by indent-
ing the second and third lines, it is easier to see they are continuations of the statement
started in the first line.
Explicitly stating the value of a variable is called assignment and is achieved with the
assignment operator =. You can assign a value to a variable in the same statement that declares
the variable, or assign the value later in another statement. For instance, in Figure 1-8, the
variable midtermScore is declared in one statement and assigned a value in a separate state-
ment. The variable finalScore is declared and assigned a value at the same time. Assigning
a value to a variable upon creation is often referred to as initializing the variable.
48. C H A P T E R O N E
21
»NOTE Unlike most other programming languages, C++ allows you to assign values to several variables in one
statement. For example, tot = sum = amount = 0; assigns a value of 0 to all three variables listed in the statement.
Assignment always takes place from right to left; that is, a value on the right side of the
assignment operator is stored in the memory location (variable) on the left side of the assign-
ment operator. Although midtermScore = 76 and 76 = midtermScore are equivalent
statements in algebra, C++ does not allow the second statement. C++ refers to locations
where values may be stored as lvalues because these values are located on the left side of
assignment statements. Lvalues are always names of memory locations—a variable is always
an lvalue, but a literal number such as 76 is not.
Figure 1-8 also shows two integer variables, quiz1Score and quiz2Score, being declared
and initialized in the same statement. After C++ programmers become accustomed to placing
a semicolon at the end of each statement, they sometimes get carried away and put a semi-
colon at the end of every line. However, sometimes a statement extends across several lines.
A declaration is complete only when you have listed as many variables as you want for that
type; use a semicolon only when the entire statement is complete.
»NOTE
Although the term
is not used as fre-
quently, rvalues are
values that appear
on the right side of
assignment state-
ments. A literal value
such as 76 can be
an rvalue, but so can
a variable (memory
location).
»NOTE
When you declare
a variable between
any set of curly
braces, the variable
is usable only from
the point of decla-
ration to the closing
curly brace. This
area is referred to
as the scope of the
variable, or the
region of the pro-
gram in which the
variable exists.
»NOTE You might have noticed that semicolons never follow function headers such as int main(). Function
headers are not C++ statements. You can think of C++ statements as full actions, so you do not place a semicolon at the
end of a function header, nor at the end of any line with a statement that continues on the next line.
»NOTE Because numeric constants that contain decimal places are doubles by default, some compilers will issue
a warning message if you assign a constant double to a float, as in float value = 12.34;. You can suppress the
warning message by using an f following the constant, as in float value = 12.34f;.
THE const QUALIFIER
A variable that does not change in a program should not be declared as a variable. (After all,
it won’t vary.) Instead, it should be a named constant—a named memory location whose
contents cannot change during execution of the program. The statement const double
MINIMUM_WAGE = 5.75; declares a constant named MINIMUM_WAGE that can be used
like a variable but cannot be changed during a program. For example, if you declare const
double MINIMUM_WAGE = 5.75; within a function, then it is illegal to write the statement
MINIMUM_WAGE = 6.00; later in the same function. The keyword const is an example of a
qualifier—a word that qualifies, or restricts, the ordinary capabilities of the named type (such
as double).
int midtermScore;
int finalScore = 100;
midtermScore = 76;
int quiz1Score = 10,
quiz2Score = 5;
Figure 1-8 Declaring, initializing, and assigning values to variables
49. AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING AND C++
Using named constants in your programs provides several advantages:
» Named constants make a program easier to understand because they describe the
purpose of the value.
» Named constants make a program easier to modify. For example, if a minimum wage
is used in several locations in a program, then changing the value of the constant
MINIMUM_WAGE is easier than searching for every instance of 5.75 in a program.
» Using named constants reduces errors when a program must be modified. For example, if
you have a named constant such as const int PAYROLL_DEPT = 6; and the department
number must be changed to 8, you just change the value of the constant and recompile
the program. If, instead, you search and replace every 6 in the program with 8, you are likely
to change some 6’s that are not department numbers at all, but instead, part of other values.
» Using named constants can reduce typographical errors. Suppose you have 12 depart-
ments in an organization. If you use the numeric constant 12 repeatedly, and in one
instance, inadvertently type 21, the wrong value will be used. However, if you have
declared const int NUM_DEPTS = 12;, and mistype NUM_DEPTS as NM_DEPTS, then
the compiler catches the error and displays an error message.
22
»NOTE In some languages, such as Java, programmers usually use all uppercase letters for a constant name; that
way, constants are easily identified in a program and not mistaken for variables. However, such capitalization is not
required. In C++, constants have traditionally been lowercase, although many programmers recommend using uppercase
identifiers, as in Java. What’s most important is that you develop a consistent style within your programs.
»NOTE Programmers refer to unnamed constants as magic numbers. In general, using magic numbers is discouraged.
Sometimes, magic numbers are acceptable. For example, if you are going to double a number, then declaring a constant
named TWO and assigning it the value 2 does not provide any advantage in your program. However, if the multiplication
factor might change later, then assigning a constant MULTIPLICATION_FACTOR makes sense.
CREATING COMMENTS
Comments are statements that do not affect the compiling or running of a program—that is,
they do not show up when the program runs. Comments are simply explanatory remarks that
the programmer includes in a program to make notes, explain programming choices, or
clarify what is taking place. These remarks are useful to other programmers who read your
programs because that might help explain the intent of a particular statement or the purpose
»TWO TRUTHS AND A LIE: WORKING WITH VARIABLES AND THE const
QUALIFIER
1. Identifiers for C++ variables can include letters, numbers, and underscores, but must begin with a letter or underscore; no
spaces or other special characters are allowed within a C++ variable name, and a variable name cannot be a keyword.
2. An int can hold a number like 47, a char can hold a character like ‘A’, and a bool can hold true or false.
3. Assigning a value to a variable upon creation is often referred to as declaring the variable.
The
false
statement
is
#3.
Assigning
a
value
to
a
variable
upon
creation
is
often
referred
to
as
initializing
the
variable.
50. C H A P T E R O N E
of the entire program. In addition, comments could indicate who wrote the program and
when. They often help the programmer remember why something was done a certain way
when the program was written weeks or months earlier.
C++ supports both line comments and block comments. A line comment begins with two
slashes (// ) and continues to the end of the line on which it is placed. It might take up an
entire line, or it might begin after some executable C++ code and take up the rest of the line. A
block comment begins with a single slash and an asterisk (/*) and ends with an asterisk and
a slash (*/ ); it might be contained on a single line or continued across many lines. Like a line
comment, a block comment might take up an entire line, or it might occur on a line along
with executable code. A block comment can be placed either before or after other code on a
line, but if a line comment appears on the same line with other code, it must follow the other
code. Figure 1-9 shows a program that contains only one executable statement: the highlighted
statement that declares the variable myAge.
23
// this is a comment on one line
/* this comment is on a different line */
/* this is in front */ int myAge; //this is in back
/* this comment runs across
three lines of code just to show
that it can be done ! */
Figure 1-9 Demonstrating comments
ANSI/ISO STANDARD C++
The C++ programming language evolved from a language named C. C++ was designed by Bjarne
Stroustrup at Bell Laboratories in the 1980s. During its early years, several compilers were devel-
oped for C++, and the language evolved in slightly different ways in different compilers. Because
of this, C++ programs written in one compiler were not always portable to another compiler.
»NOTE
When using block
comments, don’t
start a comment
that never ends.
Using /* without a
corresponding end
*/ makes every-
thing following the
/* in the program
a nonexecuting
comment.
»NOTE
Throughout this text,
comments are used
to point out features
in code examples.
Sometimes a com-
ment even indicates
that a statement is
invalid. This type of
comment is for
instruction only; you
wouldn’t use such
comments in profes-
sional programs.
»NOTE The end of a function is sometimes hard to notice because the single closing curly brace on a line by itself
does not stand out. Some programmers help mark the end of a function by placing a comment to the right of the closing
curly brace, such as the following:
} // end of main function
»TWO TRUTHS AND A LIE: CREATING COMMENTS
1. A line comment begins with two slashes (//) and ends with two backslashes ().
2. A block comment begins with a single slash and an asterisk (/*) and ends with an asterisk and a slash (*/).
3. Both line and block comments can appear on the same line as regular code.
The
false
statement
is
#1.
A
line
comment
begins
with
two
slashes
(//)
and
continues
to
the
end
of
the
line
on
which
it
is
placed.
51. AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING AND C++
In the early 1990s, a joint committee of the American National Standards Institute (ANSI)
and the International Standard Organization (ISO) standardized the syntax used in C++. The
standardized rules are known as the ANSI/ISO Standard. Most newer compilers use the
new standard, most older compilers use the older standard, and some compilers allow you to
use whichever you prefer. The features of the language are almost entirely the same using any
C++ compiler, but to access certain features, notably input and output operations, you must
begin your C++ programs with slightly different statements.
USING LIBRARIES, PREPROCESSOR DIRECTIVES,
AND NAMESPACE
C++ programs often refer to variables and code that lie outside the source code the program-
mer actually writes. C++ is powerful in part because many of its functions have already been
written for you. For example, finding the square root of a number can be a fairly complicated
mathematical task, but the creators of C++ have written a function that calculates square
roots. You can include this function, sqrt(), in your own C++ programs—but only if your
programs can find it when you link to outside files to create executable files.
Header files are files that contain predefined values and routines, such as sqrt(). Their
filenames usually have no extension or end in .h. In order for your C++ program to use these
predefined routines, you must include a preprocessor directive—a statement that tells a
program, called the preprocessor, what to do before compiling the program. In C++, all
preprocessor directives begin with a pound sign (#), which is also called an octothorp.
The #include preprocessor directive tells the compiler to include a file as part of the
finished product. In any program, you might include a special-purpose file you wrote, or
you might include a file that is packaged with your C++ compiler. For example, to use the
sqrt()function, you might use #include <math.h> or #include <cmath> depend-
ing on whether your compiler is old or new. You will need another include directive,
#include <iostream.h> or #include <iostream>, to use C++ input and output
statements.
24
»NOTE The angle brackets in #include <math.h> indicate that the math.h file is found in the standard folder that
holds include files. You could use quotation marks in place of the angle brackets, but the compiler would take a little longer
to find your file, and you would be using an unconventional format for the include statement.
»NOTE Be careful that you do not include spaces around the filename within the angle brackets in an include
statement. The compiler will search for a filename that begins and ends with spaces, and will not be able to find the file
you intend to include.
»NOTE
Do not include a
semicolon at the
end of any pre-
processor directive.
A preprocessor
directive is not a
C++ statement.
To use specific C++ features in ANSI/ISO C++, you must also learn to access a namespace.
A namespace is a mechanism for grouping features you want to include in a program. For
example, to use the standard C++ input and output statements (which you will learn about
in the next section), you can type the following near the top of your program file:
using namespace std;
52. C H A P T E R O N E
This book uses the ANSI/ISO Standard, but you might see C++ programs that follow the
older conventions. You will certainly be able to understand older C++ programs if you
encounter them; the differences are minor and are summarized in Table 1-2.
25
ANSI/ISO C++ Standard C++
The include preprocessor directives do The include preprocessor directives
not typically use file extensions, for example typically use file extensions, for example
#include<iostream> #include<iostream.h>
Uses the statement using namespace std; Does not use the using namespace std; statement
The main() function header is int main() The main()function header might be any
of the following:
int main()
int main(void)
void main()
void main(void)
It is conventional to end the main()function The main()function does not have a return
with return 0;. However, the main() statement if the function type (first word in the
function does not require a return header) is void. The main()function ends with a
statement; one is automatically generated statement such as return 0; if the main()
if you leave it out. function type is int.
Table 1-2 Differences between ANSI/ISO C++ programs and Standard C++ programs
PRODUCING C++ OUTPUT
C++ provides several objects for producing output. The simplest object is called cout,
pronounced “see out.” The name comes from Console OUTput and cout shows whatever
is passed to it. When contained in a complete C++ program, the statement cout << "Hi
there"; places the phrase “Hi there” on the monitor. The insertion operator (<<) says
“insert whatever is to my right into the object cout.”
»TWO TRUTHS AND A LIE: ANSI/ISO STANDARD C++
1. The standardized rules for C++ syntax are known as the ANSI/ISO Standard.
2. C++ is powerful because you can create all the functions you need without having to learn about any prewritten ones.
3. A namespace is a mechanism for grouping features you want to include in a program.
The
false
statement
is
#2.
C++
is
powerful
in
part
because
many
of
its
functions
have
already
been
written
for
you
and
you
can
include
them
in
your
programs.
53. AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING AND C++
The object cout is contained in the header file iostream (in ANSI/ISO C++) or iostream.h
(in Standard C++). The term iostream is short for Input Output STREAM. The preprocessor
directive to #include one of the iostream files must appear at the top of any program that
uses cout. Two complete programs that print “Hi there” are shown in Figure 1-10. If you type
one of these programs into a C++ editor, compile it, and run it, the words “Hi there” will
appear on the monitor.
26
»NOTE If you think like a computer (rather than a person), the direction of the brackets used with cout makes
sense. In the statement cout << "Hi there"; the phrase is being sent to the output device, so the insertion symbol
points to and inserts characters into the cout object.
»NOTE
You can omit the
spaces surround-
ing the insertion
operator and your
programs will still
work as expected.
Including spaces
makes statements
easier to read.
»NOTE
A phrase such as
“Hi there” that is
included within
double quotes is a
string. You will
learn more about
strings in Chapter 5.
// Program that displays "Hi there" using an ANSI/ISO C++ compiler
#include<iostream>
using namespace std;
int main()
{
cout << "Hi there";
return 0;
}
// Program that displays "Hi there" using a Standard C++ compiler
#include<iostream.h>
int main()
{
cout << "Hi there";
return 0;
}
Figure 1-10 Programs that use cout
You can see in Figure 1-10 that the programs are very similar. The only differences are in the
extension in the included filename and the addition of the using namespace std; statement
in the ANSI/ISO version. To avoid much duplication, the examples in the rest of this text will
use the ANSI/ISO versions.
You could replace the cout statement in Figure 1-10 with two cout statements:
cout << "Hi ";
cout << "there";
Even though this replacement version of the program uses two cout statements, nothing
indicates that any output should be placed on a new line. The character string “Hi ” (notice
»NOTE With some compilers, the screen output appears but is gone so quickly that you don’t get a chance to read
the output message. If this happens to you, include the line #include<conio> or #include<conio.h> as the first line
in your file, and include the line getch(); immediately after the statement cout << "Hi there";. This pauses the
execution of your program and waits for one character to be input from the keyboard before the output screen closes.
54. C H A P T E R O N E
the space included before the last quotation mark) would print on the monitor, followed
immediately by the character string “there”. To indicate a newline character—that is, the invis-
ible character that forces the next output to appear on a new line—you can use the escape
sequence n. The backslash removes the usual meaning of the letter n (which is simply to pro-
duce the letter n, as in the statement cout << 'n';) and causes the output to move to a new
line. The statement cout << "Hinthere"; shows “Hi” and “there” on two separate lines.
27
»NOTE An escape sequence is a sequence of characters in which the first character serves only to “escape” from
the usual meaning of the second character. Other commonly used escape sequences are t for Tab, ” for a double quote,
and ’ for a single quote. To actually show a backslash, use .
Another way to advance output to a new line is to use the end line manipulator endl.
Inserting endl into the output stream causes a new line plus all waiting output to become
visible, a process called flushing the buffer. The following code produces “Hi” and “there”
on two separate lines:
cout << "Hi";
cout << endl;
cout << "there";
A single cout object might show more than one item, as long as each item is preceded by its
own insertion symbol. For example, cout << "Hi" << endl << "there"; displays “Hi”,
goes to a new line, and displays “there” on the next line.
In addition to strings, you can output numbers and variables. Thus, the following three
statements of code together produce 1, 2, 3, and 4, each displayed on its own line.
int number = 3;
cout << 1 << endl;
cout << 2 << endl << number << endl << 4 << endl;
»NOTE
It’s a good idea to
add an endl
manipulator to the
end of the last cout
statement in every
C++ program.
When you do so,
you make sure that
all waiting output is
displayed before
the program ends.
PROVIDING C++ INPUT
A program in which the programmer predetermines all variable values is not very useful.
Many programs rely on input from a user—a person who runs, and probably benefits from,
the output provided by a program. These are called interactive programs because the user
interacts with the program statements. The program must provide a way for the user to enter
»TWO TRUTHS AND A LIE: PRODUCING C++ OUTPUT
1. C++ provides several objects for producing output; the simplest object is called cout, and it is used with an insertion
operator.
2. To indicate a new line of output in a C++ program you can use the newline character ('n') or the endl manipulator.
3. You can use the newline character or endl in a statement, but not both.
The
false
statement
is
#3.
You
can
mix
newline
characters
and
endl
manipulators
in
a
statement.
56. la ruiner. Ce principe est la royauté comme suzeraineté féodale.
Saint Louis dit expressément dans ses Établissements (liv. II, c.
XXVII): Se aucun se plaint en la court le roy de son saignieur de
dete que son saignieur li doie, ou de promesses, ou de convenances
que il li ait fetes, li sires m'aura mie la cour: car nus sires ne doit
estre juges, ne dire droit en sa propre querelle, selonc droit escrit en
Code: «Ne quis in sua causa judicet», en la loi unique qui commence
Generali, el rouge, et el noir, etc. Les Établissements de saint Louis
étaient faits pour les domaines du roi. Beaumanoir, dans la Coutume
de Beauvoisis, dans un livre fait pour les domaines d'un fils de saint
Louis, de Robert de Clermont, ancêtre de la maison de Bourbon,
écrit sous Philippe-le-Bel que le roi a droit de faire des
établissements, non pour ses domaines seulement, mais pour tout le
royaume. Il faut voir dans le texte même avec quelle adresse il
présente cette opinion scandaleuse et paradoxale[36].
Philippe-le-Hardi avait facilité aux roturiers l'acquisition des biens
féodaux. Il enjoignit aux gens de justice «de ne pas molester les non
nobles qui acquerront des choses féodales.» Le non-noble ne
pouvant s'acquitter des services nobles qui étaient attachés au fief, il
fallait le consentement de tous les seigneurs médiats, de degré en
degré jusqu'au roi. Philippe III réduisit à trois le nombre des
seigneurs médiats dont le consentement était requis.
La tendance de cette législation s'explique aisément quand on sait
quels furent les conseillers des rois aux treizième et quatorzième
siècles, quand on connaît la classe à laquelle ils appartenaient.
Le chambellan, le conseiller de Philippe-le-Hardi, fut le barbier ou
chirurgien de saint Louis, le Tourangeau Pierre La Brosse. Son frère,
évêque de Bayeux, partagea sa puissance et aussi sa ruine. La
Brosse avait accusé la seconde femme de Philippe III d'avoir
empoisonné un fils du premier lit. Le parti des seigneurs, à la tête
duquel était le comte d'Artois, soutint que le favori calomniait la
reine, et que de plus il vendait aux Castillans les secrets du roi. La
57. Brosse décida le roi à interroger une béguine, ou mystique de
Flandre. Le parti des seigneurs opposa à la béguine les dominicains,
généralement ennemis des mystiques. Un dominicain apporta au roi
une cassette où l'on vit ou crut voir des preuves de la trahison de La
Brosse. Son procès fut instruit secrètement. On ne manqua pas de le
trouver coupable. Les chefs du parti de la noblesse, le comte
d'Artois, une foule de seigneurs, voulurent assister à son exécution.
En tête des conseillers de saint Louis, plaçons Pierre de Fontaines,
l'auteur du Conseil à mon ami, livre en grande partie traduit des lois
romaines. De Fontaines, natif du Vermandois, en était bailli l'an
1253. Nous le voyons ensuite parmi les Maistres du parlement de
Paris. En cette qualité, il prononce un jugement en faveur du roi
contre l'abbé de Saint-Benoît-sur-Loire, puis un autre, et toujours
favorable au roi contre les religieux du bois de Vincennes. Dans ces
jugements, nous le trouvons nommé après le chancelier de
France[37]. Il s'intitule chevalier. Ce qui, dès cette époque, ne prouve
pas grand'chose. Ces gens de robe longue prirent de bonne heure le
titre de chevaliers ès lois.
Rien n'indique non plus que Philippe de Beaumanoir, bailli de
Senlis, l'auteur de ce grand livre des Coutumes de Vermandois, ait
été de bien grande noblesse. La maison du même nom est une
famille bretonne, et non picarde, qui apparaît dans les guerres des
Anglais au quatorzième siècle, mais qui ne fait pas remonter
régulièrement sa filiation plus haut que le quinzième.
Les deux frères Marigni, si puissants sous Philippe-le-Bel,
s'appelaient de leur vrai nom de famille Le Portier[38]. Ils étaient
Normands, et achetèrent dans leur pays la terre de Marigni. Le plus
célèbre des deux, chambellan et trésorier du roi, capitaine de la Tour
du Louvre, est appelé Coadjuteur et gouverneur de tout le royaume
de France. «C'était, dit un contemporain, comme un second roi, et
tout se faisait à sa volonté[39].» On n'est pas tenté de soupçonner
ce témoignage d'exagération lorsqu'on sait que Marigni mit sa statue
au Palais de Justice à côté de celle du roi[40].
58. Au nombre des ministres de Philippe-le-Bel, il faut placer deux
banquiers florentins, auxquels sans doute on doit rapporter en
grande partie les violences fiscales de ce règne. Ceux qui dirigèrent
les grands et cruels procès de Philippe-le-Bel furent le chancelier
Pierre Flotte, qui eut l'honneur d'être tué, tout comme un chevalier,
à la bataille de Courtrai. Il eut pour collègues ou successeurs Plasian
et Nogaret. Celui-ci, qui acquit une célébrité si tragique, était né à
Caraman en Lauraguais. Son aïeul, si l'on en croit les invectives de
ses ennemis, avait été brûlé comme hérétique. Nogaret fut d'abord
professeur de droit à Montpellier, puis juge mage de Nîmes. La
famille Nogaret, si fière au seizième siècle, sous le nom d'Épernon,
n'était pas encore noble en 1372, ni de l'une, ni de l'autre ligne. Peu
après cette expédition hardie où Guillaume Nogaret alla mettre la
main sur le pape, il devint chancelier et garde des sceaux. Philippe-
le-Long révoqua les dons qui lui avaient été faits par Philippe-le-Bel;
mais il ne fut pas enveloppé dans la proscription de Marigni. On eût
craint sans doute de porter atteinte à ses actes judiciaires, qui
avaient une si grande importance pour la royauté.
Ces légistes qui avaient gouverné les rois anglais dès le douzième
siècle, au treizième saint Louis, Alphonse X et Frédéric II, furent,
sous le petit-fils de saint Louis les tyrans de la France. Ces chevaliers
en droit, ces âmes de plomb et de fer, les Plasian, les Nogaret, les
Marigni, procédèrent avec une horrible froideur dans leur imitation
servile du droit romain et de fiscalité impériale. Les Pandectes
étaient leur Bible, leur Évangile. Rien ne les troublait dès qu'ils
pouvaient répondre à tort ou à droit: Scriptum est... Avec des textes,
des citations, des falsifications, ils démolirent le moyen âge,
pontificat, féodalité, chevalerie. Ils allèrent hardiment appréhender
au corps le pape Boniface VIII; ils brûlèrent la croisade elle-même
dans la personne des Templiers.
Ces cruels démolisseurs du moyen âge sont, il coûte de l'avouer,
les fondateurs de l'ordre civil aux temps modernes. Ils organisent la
centralisation monarchique. Ils jettent dans les provinces des baillis,
des sénéchaux, des prévôts, des auditeurs, des tabellions, des
59. procureurs du roi, des maîtres et peseurs de monnaie. Les forêts
sont envahies par les verdiers, les gruiers royaux. Tous ces gens
vont chicaner, décourager, détruire les juridictions féodales. Au
centre de cette vaste toile d'araignée, siège le conseil des légistes
sous le nom de parlement (fixé à Paris en 1302). Là, tout viendra
peu à peu se perdre, s'amortir sous l'autorité royale. Ce droit laïque
est surtout ennemi du droit ecclésiastique. Au besoin, les légistes
appelleront à eux les bourgeois. Eux-mêmes ne sont pas autre
chose, quoiqu'ils mendient l'anoblissement, tout en persécutant la
noblesse.
Cette création du gouvernement coûtait certainement fort cher.
Nous n'avons pas ici de détails suffisants; mais nous savons que les
sergents des prévôts, c'est-à-dire les exécuteurs, les agents de cette
administration si tyrannique à sa naissance, avaient d'abord, le
sergent à cheval trois sols parisis, et plus tard six sols; le sergent à
pied dix-huit deniers, etc. Voilà une armée judiciaire et
administrative. Tout à l'heure vont venir des troupes mercenaires.
Philippe-de-Valois aura à la fois plusieurs milliers d'arbalétriers
génois. D'où tirer les sommes énormes que tout cela doit coûter?
L'industrie n'est pas née encore. Cette société nouvelle se trouve
déjà atteinte du mal dont mourut la société antique. Elle consomme
sans produire. L'industrie et la richesse doivent sortir à la longue de
l'ordre et de la sécurité. Mais cet ordre est si coûteux à établir, qu'on
peut douter pendant longtemps s'il n'augmente pas les misères qu'il
devait guérir.
Une circonstance aggrave infiniment ces maux. Le seigneur du
moyen âge payait ses serviteurs en terres, en produits de la terre;
grands et petits, ils avaient place à sa table. La solde, c'était le repas
du jour. L'immense machine du gouvernement royal qui substitue
son mouvement compliqué aux mille mouvements naturels et
simples du gouvernement féodal; cette machine, l'argent seul peut
lui donner l'impulsion. Si cet élément vital manque à la nouvelle
royauté, elle va périr, la monarchie se dissoudra, et toutes les parties
60. retomberont dans l'isolement, dans la barbarie du gouvernement
féodal.
Ce n'est donc pas la faute de ce gouvernement s'il est avide et
affamé. La faim est sa nature, sa nécessité, le fond même de son
tempérament. Pour y satisfaire, il faut qu'il emploie tour à tour la
ruse et la force. Il y a ici en un seul prince, comme dans le vieux
roman, maître Renard et maître Isengrin.
Ce roi, de sa nature, n'aime pas la guerre, il est juste de le
reconnaître; il préfère tout autre moyen de prendre, l'achat, l'usure.
D'abord il trafique, il échange, il achète; le fort peut dépouiller ainsi
honnêtement des amis faibles. Par exemple, dès qu'il désespère de
prendre l'Espagne avec des bulles du pape, il achète du moins le
patrimoine de la branche cadette d'Aragon, la bonne ville de
Montpellier, la seule qui restât au roi Jacques. Le prince, avisé et
bien instruit en lois, ne se fit pas scrupule d'acquérir ainsi le dernier
vêtement de son prodigue ami, pauvre fils de famille qui vendait son
bien pièce à pièce, et auquel sans doute il crut devoir en ôter le
maniement en vertu de la loi romaine: Prodigus et furiosus[41].....
Au Nord, il acquit Valenciennes, qui se donna à lui (1293). Et sans
doute il y eut encore de l'argent en cela. Valenciennes l'approchait
de la riche Flandre, si bonne à prendre, et comme riche, et comme
alliée des Anglais. Du côté de la France anglaise, il avait acheté au
nécessiteux Édouard Ier
le Quercy, terre médiocre, sèche et
montagneuse, mais d'où l'on descend en Guyenne. Édouard était
alors empêtré dans les guerres de Galles et d'Écosse, où il ne
gagnait que de la gloire. C'eût été beaucoup, il est vrai, de fonder
l'unité britannique, de se fermer dans l'île. Édouard y fit d'héroïques
efforts, et commit aussi d'incroyables barbaries. Mais il eut beau
briser les harpes de Galles, tuer les bardes, il eut beau faire périr le
roi David du supplice des traîtres, et transporter à Westminster le
palladium de l'Écosse, la fameuse pierre de Scone, il ne put rien finir
ni dans l'île ni sur le continent. Chaque fois qu'il regardait vers la
France et voulait y passer, il apprenait quelque mauvaise nouvelle du
61. Border écossais ou des Marches de Galles, quelque nouveau tour de
Leolyn ou de Wallace. Wallace était encouragé par Philippe-le-Bel, le
chef héroïque des clans par le roi procureur. Celui-ci n'avait que faire
de bouger. Il lui suffisait de relancer Édouard par ses limiers
d'Écosse. Il le laissait volontiers s'immortaliser dans les déserts de
Galles et de Northumberland, procédait contre lui à son aise, et le
condamnait par défaut.
Ainsi, quand il le vit occupé à contenir l'Écosse sous Baillol, il le
somma de répondre des pirateries de ses Gascons sur nos
Normands. Il ajourna ce roi, ce conquérant, à venir s'expliquer par-
devant ce qu'il appelait le tribunal des pairs. Il le menaça, puis il
l'amusa, lui offrit une princesse de France pour prix d'une soumission
fictive, d'une simple saisie, qui arrangerait tout. L'arrangement fut
que l'Anglais ouvrit ses places, que Philippe les garda, et retira ses
offres. Cette grande province, ce royaume de Guyenne, fut
escamoté.
Édouard cria en vain. Il demanda et obtint contre Philippe
l'alliance du roi des Romains, Adolphe de Nassau, celle des ducs de
Bretagne et de Brabant, des comtes de Flandre, de Bar et de
Gueldres. Il écrivit humblement à ses sujets de Guyenne, leur
demandant pardon d'avoir consenti à la saisie[42]. Mais, trop occupé
en Écosse, il ne vint pas lui-même en Guyenne, et son parti
n'éprouva que des revers. Philippe eut pour lui le pape (Boniface
VIII), qui lui devait la tiare, et qui, pour lui donner un allié, délia le
roi d'Écosse des serments qu'il avait prêtés au roi d'Angleterre. Enfin,
il fit si bien que les Flamands, mécontents de leur comte,
l'appelèrent à leur secours. Pour soutenir la guerre, les deux rois
comptaient sur la Flandre. La grasse Flandre était la tentation
naturelle de ces gouvernements voraces. Tout ce monde de barons,
de chevaliers, que les rois de France sevraient de croisades et de
guerres privées, la Flandre était leur rêve, leur poésie, leur
Jérusalem. Tous étaient prêts à faire un joyeux pèlerinage aux
magasins de Flandre, aux épices de Bruges, aux fines toiles d'Ypres,
aux tapisseries d'Arras.
62. Il semble que Dieu ait fait cette bonne Flandre, qu'il l'ait placée
entre tous pour être mangée des uns ou des autres. Avant que
l'Angleterre fût cette chose colossale que nous voyons, la Flandre
était une Angleterre; mais de combien déjà inférieure et plus
incomplète! Drapiers sans laine, soldats sans cavalerie, commerçants
sans marine. Et aujourd'hui, ces trois choses, bestiaux, chevaux,
marine, c'est justement le nerf de l'Angleterre; c'est la matière, le
véhicule, la défense de son industrie.
Ce n'est pas tout. Ce nom, les Flandres, n'exprime pas un peuple,
mais une réunion de plusieurs pays fort divers, une collection de
tribus et de villes. Rien n'est moins homogène. Sans parler de la
différence de race et de langue, il y a toujours eu haine de ville à
ville, haine entre les villes et les campagnes, haine de classes, haine
de métiers, haine entre le souverain et le peuple[43]. Dans un pays
où la femme héritait et transférait la souveraineté, le souverain était
souvent un mari étranger. La sensualité flamande, la matérialité de
ce peuple de chair, apparaît dans la précoce indulgence de la
coutume de Flandre pour la femme et pour le bâtard[44]. La femme
flamande amena ainsi par mariage des maîtres de toute nation, un
Danois, un Alsacien; puis un voisin du Hainaut, puis un prince de
Portugal, puis des Français de diverses branches: Dampierre
(Bourbon), Louis de Mâle (Capet), Philippe-le-Hardi (Valois); enfin
Autriche, Espagne, Autriche encore. Voici maintenant la Flandre sous
un Saxon (Cobourg).
La Flandre se plaignait du comte français Gui Dampierre. Philippe
s'offrit comme protecteur aux Flamands. Gui s'adressa aux Anglais,
et voulut donner sa fille Philippa au fils d'Édouard. Ce mariage contre
le roi de France ne pouvait, selon la loi féodale, se faire sans
l'assentiment du roi de France, suzerain de Gui Dampierre. Philippe
cependant ne réclama pas; il déclara hypocritement qu'étant parrain
de la jeune fille, il ne pouvait lui laisser passer le détroit sans
l'embrasser[45]. Refuser, c'était déclarer la guerre, et trop tôt. Venir,
c'était risquer de rester à Paris. Gui vint en effet et resta. Le père et
la fille furent retenus à la Tour du Louvre. Philippe enleva à Édouard
63. son allié et sa femme, comme il avait fait la Guyenne. Le comte
s'échappa, il est vrai, dans la suite. La jeune fille mourut, au grand
dommage de Philippe, qui avait intérêt à garder un tel otage et
qu'on accusa de sa mort.
Édouard croyait avoir ameuté tout le monde contre son déloyal
ennemi. L'empereur Adolphe de Nassau, pauvre petit prince, malgré
son titre, eût volontiers guerroyé aux gages d'Édouard, comme
autrefois Othon de Brunswick pour Jean, comme plus tard
Maximilien pour Henri VIII à cent écus par jour. Les comtes de
Savoie, d'Auxerre, Montbéliard, Neuchâtel, ceux de Hainaut et de
Gueldres, le duc de Brabant, les évêques de Liège et d'Utrecht,
l'archevêque de Cologne, tous promettaient d'attaquer Philippe, tous
recevaient l'argent anglais, et tous restèrent tranquilles, excepté le
comte de Bar. Édouard les payait pour agir, Philippe pour se reposer.
La guerre se faisait ainsi sans bruit ni bataille. C'était une lutte de
corruption, une bataille d'argent, à qui serait le premier ruiné. Il
fallait donner aux amis, donner aux ennemis. Faibles et misérables
étaient les ressources des rois d'alors pour suffire à de telles
dépenses. Édouard et Philippe chassèrent, il est vrai, les juifs, en
gardant leurs biens[46]. Mais le juif est glissant, il ne se laisse pas
prendre. Il écoulait de France, et trouvait moyen d'emporter. Le roi
de France, qui avait des banquiers italiens pour ministres, s'avisa,
sans doute par leur conseil, de rançonner les Italiens, les Lombards,
qui exploitaient la France, et qui étaient comme une variété de
l'espèce juive. Puis, pour atteindre plus sûrement encore tout ce qui
achetait et vendait, le roi essaya pour la première fois de ce triste
moyen si employé dans le quatorzième siècle, l'altération de la
monnaie. C'était un impôt facile et tacite, une banqueroute secrète
au moins dans les premiers moments. Mais bientôt tous en
profitaient; chacun payait ses dettes en monnaie faible. Le roi y
gagnait moins que la foule des débiteurs sans foi. Enfin, l'on eut
recours à un moyen plus direct, l'impôt universel de la maltôte[47].
64. Ce vilain nom, trouvé par le peuple, fut accepté hardiment du roi
même. C'était un dernier moyen, une invention par laquelle, s'il
restait encore quelque substance, quelque peu à sucer dans la
moelle du peuple, on y pouvait atteindre. Mais on eut beau presser
et tordre. Le patient était si sec, que la nouvelle machine n'en put
exprimer presque rien. Le roi d'Angleterre ne tirait rien des siens non
plus. Sa détresse le désespérait; dans l'un de ses parlements on le
vit pleurer.
Entre ce roi affamé et ce peuple étique, il y avait pourtant
quelqu'un de riche. Ce quelqu'un, c'était l'Église. Archevêques et
évêques, chanoines et moines, moines anciens de Saint-Benoît,
moines nouveaux dits mendiants, tous étaient riches et luttaient
d'opulence. Tout ce monde tonsuré croissait des bénédictions du ciel
et de la graisse de la terre. C'était un petit peuple heureux, obèse et
reluisant, au milieu du grand peuple affamé qui commençait à le
regarder de travers.
Les évêques allemands étaient des princes et levaient des armées.
L'Église d'Angleterre possédait, dit-on, la moitié des terres de l'île.
Elle avait, en 1337, sept cent trente mille marcs de revenus.
Aujourd'hui, il est vrai, l'archevêque de Cantorbery ne reçoit par an
que douze cent mille francs, et celui d'York huit cent mille. Lorsque
la Restauration préparait l'expédition d'Espagne, en 1822, l'on apprit
que l'archevêque de Tolède faisait distribuer chaque jour à la porte
de ses fermes et de ses palais dix mille soupes, et celui de Séville six
mille[48].
La confiscation de l'Église fut la pensée des rois depuis le
treizième siècle, la cause principale de leurs luttes contre les papes;
toute la différence, c'est que les protestants prirent, et que les
catholiques se firent donner. Henri VIII employa le schisme, François
Ier
le Concordat.
Qui donc, au quatorzième siècle, du roi ou de l'Église, devait
désormais exploiter la France? telle était la question. Déjà, lorsque
65. Philippe mit sur le peuple le terrible impôt de la maltôte, lorsqu'il
altéra les monnaies, lorsqu'il dépouilla les Lombards, sujets ou
banquiers du Saint-Siège, il frappait Rome directement ou
indirectement, il la ruinait, il lui coupait les vivres[49].
Boniface usa enfin de représailles. En 1296, dans sa bulle Clericis
laïcos, il déclare excommuniés de fait tout prêtre qui payera, tout
laïque qui exigera subvention, prêt ou don sans l'autorisation du
Saint-Siège; et cela sans qu'aucun rang, aucun privilège puisse les
excepter. Il annulait ainsi un privilège important de nos rois, qui, tout
excommuniés qu'ils étaient comme rois, pouvaient toujours, dans
leur chapelle et portes closes, entendre la messe et communier.
Au même moment, sous prétexte de la guerre d'Angleterre,
Philippe défendait d'exporter du royaume or, argent, armes, etc.
C'était frapper Rome bien plus que l'Angleterre.
Rien de plus mystiquement hautain, de plus paternellement hostile
que la bulle en réponse: «Dans la douceur d'un ineffable amour
(Ineffabilis amoris dulcedine sponso suo), l'Église, unie au Christ,
son époux, en a reçu les dons, les grâces les plus amples,
spécialement le don de liberté. Il a voulu que l'adorable épouse
régnât, comme mère, sur les peuples fidèles. Qui donc ne redoutera
de l'offenser, de la provoquer? Qui ne sentira qu'il offense l'époux
dans l'épouse? Qui osera porter atteinte aux libertés ecclésiastiques,
contre son Dieu et son Seigneur? Sous quel bouclier se cachera-t-il,
pour que le marteau de la puissance d'en haut ne le réduise en
poudre et en cendre?... Ô mon fils, ne détourne point l'oreille de la
voix paternelle, etc.»
Il engage ensuite le roi à bien examiner sa situation: «Tu n'as
point considéré avec prudence les régions et les royaumes qui
entourent le tien, les volontés de ceux qui les gouvernent, ni peut-
être les sentiments de tes sujets dans les diverses parties de tes
États. Lève les yeux autour de toi, et regarde, et réfléchis. Songe
que les royaumes des Romains, des Anglais, de l'Espagne,
66. t'entourent de toutes parts; songe à leur puissance, à la bravoure, à
la multitude de leurs habitants, et tu reconnaîtras aisément que ce
n'était pas le temps, que ce n'était pas le jour d'attaquer, d'offenser
et nous et l'Église par de telles piqûres... Juge toi-même quelles ont
dû être les pensées du Siège apostolique, lorsque dans ces jours
même où nous étions occupés de l'examen et de la discussion des
miracles qu'on attribue à l'invocation de ton aïeul de glorieuse
mémoire, tu nous as envoyé de tels dons qui provoquent la colère
de Dieu, et méritent, je ne dis pas seulement notre indignation, mais
celle de l'Église elle-même...
«Dans quel temps tes ancêtres et toi-même avez-vous eu recours
à ce Siège, sans que votre pétition fût écoutée? Et si une grave
nécessité menaçait de nouveau ton royaume, non seulement le
Saint-Siège t'accorderait les subventions des prélats et des
personnes ecclésiastiques; mais, si le cas l'exigeait, il étendrait ses
mains jusqu'aux calices, aux croix et aux vases sacrés, plutôt que de
ne pas défendre efficacement un tel royaume, qui est si cher au
Saint-Siège, et qui lui a été si longtemps dévoué.... Nous exhortons
donc Ta Sérénité royale, la prions et l'engageons à recevoir avec
respect les médicaments que t'offre une main paternelle, à
acquiescer à des avis salutaires pour toi et pour ton royaume, à
corriger tes erreurs, et à ne point laisser séduire ton âme par une
fausse contagion. Conserve notre bienveillance et celle du Saint-
Siège, conserve une bonne renommée parmi les hommes, et ne
nous force point à recourir à d'autres remèdes, à des remèdes
inusités; lors même que la justice nous y forcerait, nous en ferait un
devoir, nous ne les emploierions qu'à regret et malgré nous[50].»
Ces graves paroles, mêlées de douceur et de menaces, devaient
faire impression. Aucun pontife n'avait été jusque-là plus partial pour
nos rois que Boniface. La maison de France l'avait fait pape, il est
vrai; mais, en retour, il la faisait reine, autant qu'il était en lui. Il
avait appelé en Italie Charles-de-Valois, et, en attendant l'empire
latin de Constantinople, il l'avait créé comte de Romagne, capitaine
du patrimoine de saint Pierre, seigneur de la marche d'Ancône. Il
67. obtint aux princes français le trône de Hongrie; il fit ce qu'il put pour
leur procurer le trône impérial et celui de Castille. En 1298, pris pour
arbitre entre les rois de France et d'Angleterre, il essaya de les
rapprocher par des mariages, et, par une sentence provisoire, il
ajourna les restitutions que Philippe devait à l'Anglais.
La papauté, toute vieillie qu'elle était déjà, apparaissait encore
comme l'arbitre du monde. Boniface VIII avait été appelé à juger
entre la France et l'Angleterre, entre l'Angleterre et l'Écosse, entre
Naples et l'Aragon, entre les empereurs Adolphe de Nassau et Albert
d'Autriche. N'y avait-il pas lieu pour le pape de se faire illusion sur
ses forces réelles?
L'infatuation fut au comble, lorsqu'en l'an 1300 Boniface promit
rémission des péchés à tous ceux qui viendraient visiter pendant
trente jours les églises des Saints-Apôtres. Ce Jubilé rappelait tout à
la fois celui des Juifs et les fêtes séculaires de Rome païenne. On sait
que le Jubilé mosaïque, revenant tous les cinquante ans, devait
rendre la liberté aux esclaves, les terres aliénées à leur premier
possesseur; il devait annuler l'histoire, défaire le temps, pour ainsi
dire, au nom du seul Éternel. La vieille Rome, dans un tout autre
point de vue, emprunta des Étrusques la doctrine des Âges[51]; mais
ce ne fut point pour y reconnaître la mobilité de ce monde, la
mortalité des empires. Rome se croyait Dieu, elle se jugeait
immortelle comme invincible, et, au retour de chaque siècle,
solennisait son éternité.
En l'an 1300, la foi était grande encore. La foule fut prodigieuse à
Rome[52]. On compta les pèlerins par cent mille, et bientôt il n'y eut
plus moyen de compter. Ni les maisons, ni les églises ne suffirent à
les recevoir; ils campèrent par les rues et les places, sous des abris
construits à la hâte, sous des toiles, sous des tentes et sous la voûte
du ciel. On eût dit que, les temps étant accomplis, la chrétienté
venait par-devant son juge dans la vallée de Josaphat.
68. Pour se représenter l'effet de ce prodigieux spectacle, il faut
encore voir Rome, toute déchue qu'elle est, il faut la voir pendant les
fêtes de Pâques. On oublierait presque que c'est bien là la triste
Rome, la veuve de deux antiquités.
Quel qu'ait été le motif de Boniface VIII, fiscal ou politique, je ne
lui en veux pas pour cette invention du Jubilé. Des milliers d'hommes
l'en ont, j'en suis sûr, remercié du cœur. C'était mettre une pierre sur
la route du temps, placer un point d'arrêt dans sa vie, entre les
regrets du passé et les espérances d'un meilleur, d'un moins
regrettable avenir; c'était s'arrêter en montant cette rude pente,
souffler un peu à midi, Nel mezzo cammin di nostra vita.
Ces âges candides croyaient qu'on pouvait fuir le mal en
changeant de lieu, voyager du péché à la sainteté, laisser le diable
avec l'habit qu'on dépose pour prendre celui du pèlerin. N'est-ce
donc pas quelque chose d'échapper à l'influence des lieux, des
habitudes, de se dépayser, de s'orienter à une vie nouvelle? N'y a-t-il
pas une mauvaise puissance d'infatuation et d'aveuglement dans ces
lieux où le cœur se prend, que ce soit les Charmettes de Jean-
Jacques, ou la Pinada de Byron, ou ce lac d'Aix-la-Chapelle dont,
selon la tradition, Charlemagne fut ensorcelé?
Ne nous étonnons pas si nos aïeux aimèrent tant les pèlerinages,
s'ils attribuèrent à la visite des lointains sanctuaires une vertu de
régénération. «Le vieillard, tout blanc et chenu, se sépare des lieux
où il a fourni sa carrière, et de sa famille alarmée qui se voit privée
d'un père chéri.—Vieux, faible et sans haleine, il se traîne comme il
peut, s'aidant de bon vouloir, tout rompu qu'il est par les ans, par la
fatigue du chemin.—Il vient à Rome pour y voir la semblance de
Celui que, là-haut encore, il espère bien revoir au ciel[53]...»
Mais il en est qui n'arrivent pas, qui restent en chemin... La
plupart de nos lecteurs se rappellent ici ce petit tableau de Robert, la
pèlerine romaine assise dans la campagne aride; elle ne voit ni ses
pieds ensanglantés, ni son nourrisson sur ses genoux, altéré et
69. haletant, pourvu qu'elle atteigne la colline bénie qui plane au loin à
l'horizon: Monte di gioja!...
Et quand le but du voyage, c'était Rome! quand au
renouvellement du siècle, au moment solennel où sonnait une heure
de la vie du monde, on atteignait la grande ville, et que ces
monuments, ces vieux tombeaux, jusque-là seulement ouïs et
célébrés, on les voyait, on les touchait; alors, se retrouvant
contemporain de tous les siècles, et des consuls et des martyrs,
ayant de station en station, du Colisée au Capitole et du Panthéon à
Saint-Pierre, revécu toute l'histoire, ayant vu toute mort et toute
ruine, on s'en allait, on se remettait en marche vers la patrie, vers le
tombeau natal, mais avec moins de regret, et d'avance tout consolé
de mourir.
L'Église, comme ces milliers d'hommes qui venaient la visiter,
trouva dans ce Jubilé de l'an 1300 le point culminant de sa vie
historique. La descente commença dès lors. Dans cette foule même
se trouvaient les hommes redoutables qui allaient ouvrir un monde
nouveau. Les uns, froids et impitoyables politiques, comme
l'historien Jean Villani; les autres, chagrins et superbes, comme
Dante, qui, lui aussi, allait se faire son Jubilé. Le pape avait appelé à
Rome tous les vivants; le poète convoqua dans sa Comédie tous les
morts; il fit la revue du monde fini, le classa, le jugea. Le moyen
âge, comme l'antiquité, comparut devant lui. Rien ne lui fut caché.
Le mot du sanctuaire fut dit et profané. Le sceau fut enlevé, brisé:
on ne l'a pas retrouvé depuis. Le moyen âge avait vécu; la vie est un
mystère, qui périt lorsqu'il achève de se révéler. La révélation, ce fut
la Divina Commedia, la cathédrale de Cologne, les peintures du
Campo Santo de Pise. L'art vient ainsi terminer, fermer une
civilisation, la couronner, la mettre glorieusement au tombeau.
N'accusons pas le pape, si cet octogénaire, vieil avocat, et nourri
dans les ruses et les plus prosaïques intrigues[54], se laissa gagner
lui-même à la grandeur, à la poésie de ce moment, où il vit le genre
humain réuni à Rome et à genoux devant lui... Il est d'ailleurs une
70. sombre puissance de vertige dans cette ville tragique. Les souverains
de Rome, ses Empereurs, ont paru souvent comme fous. Et même
au quatorzième siècle, Cola Rienzi, le fils d'une blanchisseuse,
devenu tribun de Rome, ne tournait-il pas son épée vers les trois
parties du globe, en disant: «Ceci et ceci, cela encore, est à moi?»
À plus forte raison, le pape se croyait-il le maître du monde.
Lorsque Albert d'Autriche se fit empereur par la mort d'Adolphe de
Nassau, Boniface, indigné, mit la couronne sur sa tête, saisit une
épée, et s'écria: «C'est moi qui suis César, c'est moi qui suis
l'empereur, c'est moi qui défendrai les droits de l'Empire.» Au Jubilé
de 1300, il parut, au milieu de cette multitude de toute nation, avec
les insignes impériaux; il fit porter devant lui l'épée et le sceptre sur
la boule du monde, et un héraut allait criant: «Il y a ici deux épées;
Pierre, tu vois ici ton successeur; et vous, ô Christ! regardez votre
vicaire.» Il expliquait ainsi les deux épées qui se trouvèrent dans le
lieu où Jésus-Christ fit la Cène avec ses apôtres.
Cette outrecuidance pontificale devait perpétuer la guerre des
deux puissances, ecclésiastique et civile. La lutte qui semblait finie
avec la maison de Souabe, est reprise par celle de France. Guerre
d'idées, non de personnes, de nécessité, non de volonté. Le pieux
Louis IX la commence, le sacrilège Philippe IV la continue.
«Reconnaître deux puissances et deux principes, dit Boniface dans
sa bulle Unam sanctam, c'est être hérétique et manichéen...» Mais le
monde du moyen âge est manichéen, il mourra tel; toujours il
sentira en lui la lutte des deux principes.—Que cherches-tu?—La
paix. C'est le mot du monde. L'homme est double; il y a en lui le
Pape et l'Empereur[55].
La paix! Elle est dans l'harmonie, sans doute; mais, d'âge en âge,
on l'a cherchée dans l'unité. Dès le second siècle, saint Irénée écrit
contre les Gnostiques son livre: De l'unité du principe du monde: De
Monarchia. C'est encore le titre de Dante: De Monarchia: De l'unité
du monde social[56].
71. Le livre de Dante est bizarre. Sa formule, c'est la paix, comme
condition du développement, la paix sous un monarque unique. Ce
monarque, possédant tout, ne peut rien désirer, et partant, il est
impeccable. Ce qui fait le mal, c'est la concupiscence; où il n'y a plus
limite, que désirer? quelle concupiscence peut naître[57]? tel est le
raisonnement de Dante. Reste à prouver que cet idéal peut être réel,
que ce réel est le peuple romain[58]; qu'enfin le peuple romain a
transmis sa souveraineté à l'empereur d'Allemagne.
Ce livre est une belle épitaphe gibeline pour l'Empire allemand:
l'Empire en 1300, ce n'est plus exclusivement l'Allemagne: c'est
désormais tout empire, toute royauté; c'est le pouvoir civil en tout
pays, surtout en France. Les deux adversaires sont maintenant
l'Église et le fils aîné de l'Église. Des deux côtés, prétentions sans
bornes: deux infinis en face. Le roi, s'il n'est pas le seul roi, est du
moins le plus grand roi du monde; le plus révéré encore depuis saint
Louis. Fils aîné de l'Église, il veut être plus âgé que sa mère: «Avant
qu'il n'y eût des clercs, dit-il, le roi avait en garde le royaume de
France[59].»
La querelle s'était déjà émue à l'occasion des biens d'Église; mais
il y avait d'autres motifs d'irritation. Boniface avait décidé entre
Philippe et Édouard, non comme ami et personne privée, mais
comme pape. Le comte d'Artois, indigné de la partialité du pontife
pour les Flamands, arracha la bulle au légat et la jeta au feu. En
représailles, Boniface favorisa Albert d'Autriche contre Charles-de-
Valois, qui prétendait à la couronne impériale. De son côté, Philippe
mit la main sur les régales de Laon, de Poitiers et de Reims. Il
accueillait les mortels ennemis de Boniface, les Colonna, ces rudes
gibelins, ces chefs des brigands romains contre les papes.
L'explosion eut lieu au sujet d'un bien mal acquis, que depuis un
siècle se disputaient le pape et le roi. Je parle de cette sanglante
dépouille du Languedoc. Boniface VIII paya pour Innocent III.
L'hommage de Narbonne, rendu directement au roi par le vicomte,
était vivement réclamé par l'archevêque (1300). L'archevêque eût
72. voulu s'arranger. Le pape le menaça d'excommunication, s'il traitait
sans la permission du Saint-Siège. Il cita à Rome l'homme du roi, et,
de plus, menaça Philippe, s'il ne se désistait du comté de Melgueil,
dont ses officiers dépouillaient l'église de Maguelone.
Ce n'est pas tout: le pape avait, malgré Philippe, créé, dans ce
dangereux Languedoc, à la porte du comte de Foix et du roi
d'Aragon, un nouvel évêché pris sur le diocèse de Toulouse, l'évêché
de Pamiers. Il avait fait évêque un homme à lui, Bernard de Saisset.
Ce fut justement ce Saisset qu'il envoya au roi pour lui rappeler sa
promesse d'aller à la croisade, et le sommer de mettre en liberté le
comte de Flandre et sa fille. De telles paroles ne se disaient pas
impunément à Philippe-le-Bel.
Ce Saisset, qui parlait si hardiment, était déjà désigné au roi, par
l'évêque de Toulouse, comme l'auteur d'un vaste complot qui eût
enlevé tout le Midi aux Français. Saisset appartenait à la famille des
anciens vicomtes de Toulouse. Il était l'ami de tous les hommes
distingués, de toute la noblesse municipale de cette grande cité. Il
rêvait la fondation d'un royaume de Languedoc au profit du comte
de Foix, ou du comte de Comminges, qui descendait des Raimonds
de Toulouse, tant regrettés de leurs anciens sujets[60].
Ces grands seigneurs du Midi n'avaient ni les forces, ni l'amour du
pays, ni la hauteur de courage, qu'une telle entreprise eût
demandés. Le comte de Comminges se signa, en entendant des
propositions si hardies: «Ce Saisset est un diable, dit-il, plutôt qu'un
homme[61].» Le comte de Foix joua un rôle plus odieux. Il reçut les
confidences de Saisset, pour les transmettre au roi par l'évêque de
Toulouse[62]. On sut par lui que Saisset se chargeait de demander
pour le fils du comte de Foix la fille du roi d'Aragon, qui, disait-il,
était son ami. Il avait dit encore: «Les Français ne feront jamais de
bien, mais plutôt du mal au pays.» Il ne voulait pas terminer avec le
comte de Foix les démêlés de son évêché, à moins que ce seigneur
ne s'arrangeât avec les comtes d'Armagnac et de Comminges, et ne
réunît ainsi tout le pays sous son influence.
73. On attribuait à Saisset des mots piquants contre le roi: «Votre roi
de France, disait-il, est un faux monnayeur. Son argent n'est que de
l'ordure... Ce Philippe-le-Bel n'est ni un homme, ni même une bête;
c'est une image, et rien de plus... Les oiseaux, dit la fable, se
donnèrent pour roi le duc, grand et bel oiseau, il est vrai, mais le
plus vil de tous. La pie vint un jour se plaindre au roi de l'épervier, et
le roi ne répondit rien (nisi quod flevit). Voilà votre roi de France;
c'est le plus bel homme qu'on puisse voir, mais il ne sait que
regarder les gens... Le monde est aujourd'hui comme mort et
détruit, à cause de la malice de cette cour... Mais saint Louis m'a dit
plus d'une fois que la royauté de France périrait en celui qui est le
dixième roi, à partir d'Hugues-Capet.»
Deux commissaires de Philippe, un laïque et un prêtre, étant
venus en Languedoc pour instrumenter contre Saisset, il comprit son
danger et voulut se sauver à Rome. Les hommes du roi ne lui en
laissèrent pas le temps. Ils le prirent de nuit, dans son lit, et
l'enlevèrent à Paris, avec ses serviteurs, qui furent mis à la torture.
Cependant le roi envoyait au pape, non pour se justifier d'avoir violé
les privilèges de l'Église, mais pour demander la dégradation de
l'évêque, avant de le mettre à mort. La lettre du roi respire une
étrange soif de sang: «Le roi requiert le souverain pontife
d'appliquer tel remède, d'exercer le dû de son office, de telle sorte
que cet homme de mort (dictus vir mortis), dont la vie souille même
le lieu qu'il habite, il le prive de tout ordre, le dépouille de tout
privilège clérical, et que le seigneur roi puisse, de ce traître à Dieu et
aux hommes, de cet homme enfoncé dans la profondeur du mal,
endurci et sans espoir de correction, que le roi en puisse par voie de
justice faire à Dieu un excellent sacrifice. Il est si pervers que tous
les éléments doivent lui manquer dans la mort, puisqu'il offense Dieu
et toute créature[63].»
Le pape réclama l'évêque, déclara suspendre le privilège
qu'avaient les rois de France de ne pouvoir être excommuniés et
convoqua le clergé de France à Rome pour le 1er
novembre de
l'année suivante. Enfin il adressa au roi la bulle Ausculta, fili:
É
74. «Écoute, mon fils, les conseils d'un père tendre...» Le pape
commençait par ces paroles irritantes, dont ses adversaires surent
bien profiter: «Dieu nous a constitué, quoique indigne, au-dessus
des rois et des royaumes, nous imposant le joug de la servitude
apostolique, pour arracher, détruire, disperser, dissiper, et pour
édifier et planter sous son nom et par sa doctrine...» Du reste, la
bulle était, sous forme paternelle, une récapitulation de tous les
griefs du pape et de l'Église.
Le chancelier Pierre Flotte se chargea de porter la réponse au
pape. La réponse, c'était que le roi ne lâchait pas son prisonnier, qu'il
le remettait seulement à garder à l'archevêque de Narbonne, que l'or
et l'argent ne sortiraient plus de France, que les prélats n'iraient
point à Rome. Ce fut une rude insulte pour le pape encore
triomphant de son Jubilé, quand ce petit avocat borgne[64] vint lui
parler si librement. L'altercation fut violente. Le pape le prit de haut:
«Mon pouvoir, dit-il, renferme les deux.» Pierre Flotte répondit par
un aigre distinguo: «Oui, mais votre pouvoir est verbal, celui du roi
réel.» Le Gascon Nogaret, qui était venu avec Pierre Flotte, ne put
se contenir; il parla avec la violence et l'emportement méridional sur
les abus de la cour pontificale, sur la conduite même du pape. Ils
sortirent ainsi de Rome, enragés dans leur haine d'avocats contre les
prêtres, ayant outragé le pape, et sûrs de périr s'ils ne le
prévenaient.
Pour soulever tout le monde contre Boniface, il fallait tirer
quelques propositions bien claires et bien choquantes du doucereux
bavardage où la cour de Rome aimait à noyer sa pensée. Ils
arrangèrent donc entre eux une brutale petite bulle où le pape
exprimait crûment toutes ses prétentions. En même temps, ils
faisaient courir une fausse réponse à la fausse bulle, où le roi parlait
au pape avec une violence et une grossièreté populacières. Cette
réponse, bien entendu, n'était pas destinée à être envoyée, mais elle
devait avoir deux effets. D'abord elle avilissait le pouvoir sacro-saint,
auquel on jetait impunément cette boue. Ensuite, elle indiquait que
le roi se sentait fort, ce qui est le moyen de l'être en effet.
75. «Boniface, évêque, serviteur des serviteurs de Dieu, à Philippe, roi
des Francs. Crains Dieu et observe ses commandements. Nous
voulons que tu saches que tu nous es soumis dans le temporel
comme dans le spirituel; que la collation des bénéfices et des
prébendes ne t'appartient point; que si tu as la garde des bénéfices
vacants, c'est pour en réserver les fruits aux successeurs. Que si tu
en as conféré quelqu'un, nous déclarons cette collation invalide, et
nous la révoquons si elle a été exécutée, déclarant hérétiques tous
ceux qui pensent autrement. Donné au Latran, aux nones de
décembre, l'an 7 de notre pontificat.» C'est la date de la bulle
Ausculta, fili.
«Philippe, par la grâce de Dieu, roi des Français, à Boniface, qui se
donne pour pape, peu ou point de salut. Que ta Très grande Fatuité
sache que nous ne sommes soumis à personne pour le temporel;
que la collation des églises et des prébendes vacantes nous
appartient par le droit royal; que les fruits en sont à nous; que les
collations faites et à faire par nous sont valides au passé et à
l'avenir; que nous maintiendrons leurs possesseurs de tout notre
pouvoir, et que nous tenons pour fous et insensés ceux qui croiront
autrement.»
Ces étranges paroles qui eussent, un siècle plus tôt, armé tout le
royaume contre le roi, furent bien reçues de la noblesse et du peuple
des villes. On fit alors un pas de plus; on compromit directement la
noblesse avec le pape. Le 11 février 1302, en présence du roi et
d'une foule de seigneurs et de chevaliers, au milieu du peuple de
Paris, la petite bulle fut brûlée, et cette exécution fut ensuite criée à
son de trompe par toute la ville[65]. Encore deux cents ans, un
moine allemand fera de son autorité privée ce que Pierre Flotte et
Nogaret font maintenant au nom du roi de France.
Mais il fallait engager tout le royaume dans la querelle. Le pape
avait convoqué les prélats à Rome pour le 1er
novembre; le roi
convoqua les États pour le 10 avril; non plus les États du clergé et
de la noblesse, non plus les États du Midi, comme saint Louis les
É É
76. avait rassemblés, mais les États du Midi et du Nord, les États des
trois ordres: clergé, noblesse et bourgeoisie des villes. Ces États
généraux de Philippe-le-Bel sont l'ère nationale de la France, son
acte de naissance. Elle a été ainsi baptisée dans la basilique de
Notre-Dame, où s'assemblèrent ces premiers États[66]. De même
que le Saint-Siège, au temps de Grégoire VII et d'Alexandre III,
s'était appuyé sur le peuple, l'ennemi du Saint-Siège appelle
maintenant le peuple à lui. Ces bourgeois, maires, échevins, consuls
des villes, sous quelque forme humble et servile qu'ils viennent
d'abord répéter les paroles du roi et des nobles, ils n'en sont pas
moins la première apparition du peuple.
Pierre Flotte ouvrit les États (10 avril 1302) d'une manière habile
et hardie. Il attaqua les premières paroles de la bulle Ausculta, fili:
«Dieu nous a constitué au-dessus des rois et des royaumes...» Puis il
demanda si les Français pouvaient, sans lâcheté, se soumettre à ce
que leur royaume, toujours libre et indépendant, fût ainsi placé dans
le vasselage du pape. C'était confondre adroitement la dépendance
morale et religieuse avec la dépendance politique, toucher la fibre
féodale, réveiller le mépris de l'homme d'armes contre le prêtre. Le
bouillant comte d'Artois, qui déjà avait arraché au légat et déchiré la
bulle Ausculta, prit la parole et dit que, s'il convenait au roi d'endurer
ou de dissimuler les entreprises du pape, les seigneurs ne les
souffriraient pas. Cette flatterie brutale, sous forme de liberté et de
hardiesse, fut applaudie des nobles. En même temps, on leur fit
signer et sceller une lettre en langue vulgaire, non au pape, mais
aux cardinaux. La lettre était probablement tout écrite d'avance par
les soins du chancelier, car elle est datée du 10 avril, du jour même
où les États furent assemblés. Dans cette longue épître, les
seigneurs, après avoir souhaité aux cardinaux «continuel
accroissement de charité, d'amour et de toutes bonnes aventures à
leur désir», déclarent que, quant aux dommages que «celuy qui en
présent est ou siège du gouvernement de l'Église», dit être faits par
le roi, ils ne veulent, «ne eux, ne les universités, ne li peuple du
royaume, avoir ne correction ne amende, par autre fors que par ledit
nostre Sire le Roi». Ils accusent «cil qui à présent siet ou siège du
É
77. gouvernement de l'Église» de tirer beaucoup d'argent de la
conférence et collation des archevêques, évêques et autres
bénéficiers, «si que li mêmes peuples, qui leur est soubgez, soient
grevez et rançonnez. Ne li prélas ne poent donner leurs bénéfices
aux nobles clercs et autres bien nez et bien lettrez de leurs dioceses,
de qui antecessours les églises sont fondées». Les seigneurs
signèrent certainement de grand cœur ce dernier mot où l'habile
rédacteur insinuait que les bénéfices, fondés pour la plupart par
leurs ancêtres, devaient être donnés à leurs cadets ou à leurs
créatures, ainsi que cela se fait en Angleterre, surtout depuis la
Réforme. C'était attacher à la défaite du pape le retour des biens
immenses dont les seigneurs s'étaient dépouillés pour l'Église dans
les âges de ferveur religieuse[67].
La lettre des bourgeois fut calquée sur celle des nobles, si nous en
jugeons par la réponse des cardinaux. Mais elle n'a pas été
conservée, soit qu'on n'ait daigné en tenir compte, soit qu'on ait
craint que le dernier des trois ordres ne tirât plus tard avantage du
langage hardi qu'on lui avait permis de prendre dans cette occasion.
La lettre des membres du clergé est tout autrement modérée et
douce. D'abord elle est adressée au pape: «Sanctissimo patri ac
domino suo carissimo...» Ils exposent les griefs du roi et réclament
son indépendance quant au temporel. Ils ont fait tout ce qu'ils ont
pu pour l'adoucir; ils l'ont supplié de permettre qu'ils allassent aux
pieds de la béatitude apostolique. Mais la réponse est venue du roi
et des barons qu'on ne leur permettrait aucunement de sortir du
royaume. Ils sont tenus au roi par leur serment de fidélité à la
conservation de sa personne, de ses honneurs et libertés, à celle des
droits du royaume, d'autant plus que nombre d'entre eux tiennent
des duchés, comtés, baronies et autres fiefs. Enfin, dans cette
nécessité extrême, ils ont recours à la providence de Sa Sainteté,
«avec des paroles pleines de larmes et des sanglots mêlés de pleurs,
implorant sa clémence paternelle, etc.».
78. Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com