Welcome to the C++ computer programming language and C++ How to Program, Tenth Edition. We believe that this book and its support materials will give you an informative, challenging and entertaining introduction to C++. The book presents leading-edge computing technologies in a friendly manner appropriate for introductory college course sequences, based on the curriculum recommendations of two key professional organizations—the ACM and the IEEE.1
If you haven’t already done so, please read the back cover and check out the additional reviewer comments on the inside back cover and the facing page—these capture the essence of the book concisely. In this Preface we provide more detail for students, instructors and professionals.
At the heart of the book is the Deitel signature live-code approach—we present most concepts in the context of complete working programs followed by sample executions, rather than in code snippets. Read the Before You Begin section to learn how to set up your Linux-based, Windows-based or Apple OS X-based computer to run the hundreds of code examples. All the source code is available at
http://www.deitel.com/books/cpphtp10
and
http://www.pearsonhighered.com/deitel
Use the source code we provide to run each program as you study it.
As you read the book, if you have questions, we’re easy to reach at
[email protected]
We’ll respond promptly. For book updates, visit
http://www.deitel.com/books/cpphtp10
Join the Deitel social media communities on
Facebook®—http:/
LinkedIn®—http:/
Twitter®—http:/
Google+™—http:/
YouTube®—http:/
and subscribe to the Deitel® Buzz Online newsletter
http://www.deitel.com/newsletter/subscribe.html
These are exciting times in the programming languages community with each of the major languages striving to keep pace with compelling new programming technologies. In the three decades of C++’s development prior to 2011, only a few new versions of the language were released. Now the ISO C++ Standards Committee is committed to releasing a new standard every three years and the compiler vendors are building in the new features promptly. C++ How to Program, 10/e is based on the C++11 and C++14 standards published in 2011 and 2014, respectively. C++17 is already under active development. Throughout the book, C++11 and C++14 features are marked with the “11” and “14” icons, respectively, that you see here in the margin. Fig. 1 lists the book’s first references to the 77 C++11 and C++14 features we discuss.
C++11 and C++14 features in C++ How to Program, 10/e |
---|
Chapter 24
|
Conforms to the C++11 standard and the new C++14 standard.
Code thoroughly tested on three popular industrial-strength C++14 compilers. We tested the code examples on GNU™ C++ 5.2.1, Microsoft® Visual Studio® 2015 Community edition and Apple® Clang/LLVM in Xcode® 7.
Smart pointers. Smart pointers help you avoid dynamic memory management errors by providing additional functionality beyond that of built-in pointers. We discuss unique_ptr
in Chapter 17, and shared_ptr
and weak_ptr
in Chapter 24.
Early coverage of Standard Library containers, iterators and algorithms, enhanced with C++11 and C++14 capabilities. The treatment of Standard Library containers, iterators and algorithms in Chapters 15 and 16 has been enhanced with additional C++11 and C++14 features. The vast majority of your data structure needs can be fulfilled by reusing these Standard Library capabilities. We’ll show you how to build your own custom data structures in Chapter 19.
Online Chapter 24, C++11 and C++14 Additional Topics. This chapter includes discussions of regular expressions, shared_ptr
and weak_ptr
smart pointers, move semantics, multithreading, tuple
s, decltype
, constexpr
and more (see Fig. 1).
Random-number generation, simulation and game playing. To help make programs more secure, we include a treatment of C++11’s non-deterministic random-number generation capabilities.
Pointers. We provide thorough coverage of the built-in pointer capabilities and the intimate relationship among built-in pointers, C strings and built-in arrays.
Visual presentation of searching and sorting, with a simple explanation of Big O.
Printed book contains core content; additional content is online. Several online chapters and appendices are included. These are available in searchable PDF format on the book’s password-protected Companion Website—see the access card information on the inside front cover.
Getting Started Videos. At http:/
, we provide links to our getting-started videos that help readers begin using Microsoft Visual Studio 2015 Community edition on Windows, Apple Xcode on OS X and GNU C++ on Linux.
Debugger appendices. On the book’s Companion Website we provide Appendix H, Using the Visual Studio Debugger, Appendix I, Using the GNU C++ Debugger and Appendix J, Using the Xcode Debugger.
Discussions of the new C++14 capabilities.
Further integration of C++11 capabilities into the code examples, because the latest compilers are now supporting these features.
Uniform initialization with list initializer syntax.
Always using braces in control statements, even for single-statement bodies:
if (condition) {
single-statement or multi-statement body
}
Replaced the Gradebook
class with Account
, Student
and DollarAmount
class case studies in Chapters 3, 4 and 5, respectively. DollarAmount
processes monetary amounts precisely for business applications.
C++14 digit separators in large numeric literals.
Type &x
is now Type& x
in accordance with industry idiom.
Type *x
is now Type* x
in accordance with industry idiom.
Using C++11 scoped enum
s rather than traditional C enum
s.
We brought our terminology in line with the C++ standard.
Key terms in summaries now appear in bold for easy reference.
Removed extra spaces inside []
, ()
, <>
and {}
delimiters.
Replaced most print
member functions with toString
member functions to make classes more flexible—for example, returning a string
gives the client code the option of displaying it on the screen, writing it to a file, concatenating it with other string
s, etc.
Now using ostringstream
to create formatted string
s for items like the string
representations of a Time
, rather than outputting formatted data directly to the standard output.
For simplicity, we deferred using the three-file architecture from Chapter 3 to Chapter 9, so all early class examples define the entire class in a header.
We reimplement Chapter 10’s Array
class operator-overloading example with unique_ptr
s in Chapter 24. Using raw pointers and dynamic-memory allocation with new
and delete
is a source of subtle programming errors, especially “memory leaks”—unique_ptr
and the other smart pointer types help prevent such errors.
Using lambdas rather than function pointers in Chapter 16, Standard Library Algorithms. This will get readers comfortable with lambdas, which can be combined with various Standard Library algorithms to perform functional programming in C++. We’re planning a more in-depth treatment of functional programming for C++ How to Program, 11/e.
Enhanced Chapter 24 with additional C++14 features.
Early-objects approach. The book introduces the basic concepts and terminology of object technology in Chapter 1. You’ll develop your first customized classes and objects in Chapter 3. We worked hard to make this chapter especially accessible to novices. Presenting objects and classes early gets you “thinking about objects” immediately and mastering these concepts more thoroughly.2
C++ Standard Library string.
C++ offers two types of strings—string
class objects (which we begin using in Chapter 3) and C-style pointer-based strings. We’ve replaced most occurrences of C strings with instances of C++ class string
to make programs more robust and eliminate many of the security problems of C strings. We continue to discuss C strings later in the book to prepare you for working with the legacy code in industry. In new development, you should favor string
objects.
C++ Standard Library array.
C++ offers three types of arrays—array
s and vector
s (which we start using in Chapter 7) and C-style, pointer-based arrays which we discuss in Chapter 8. Our primary treatment of arrays uses the Standard Library’s array
and vector
class templates instead of built-in, C-style, pointer-based arrays. We still cover built-in arrays because they remain useful in C++ and so that you’ll be able to read legacy code. In new development, you should favor class template array
and vector
objects.
Crafting valuable classes. A key goal of this book is to prepare you to build valuable reusable classes. Chapter 10 begins with a test-drive of class template string
so you can see an elegant use of operator overloading before you implement your own customized class with overloaded operators. In the Chapter 10 case study, you’ll build your own custom Array
class, then in the Chapter 18 exercises you’ll convert it to a class template. You will have truly crafted valuable classes.
Case studies in object-oriented programming. We provide several well-engineered real-world case studies, including the Account
class in Chapter 3, Student
class in Chapter 4, DollarAmount
class in Chapter 5, GradeBook
class in Chapter 7, the Time
class in Chapter 9, the Employee
class in Chapters 11–12 and more.
Optional case study: Using the UML to develop an object-oriented design and C++ implementation of an ATM. The UML™ (Unified Modeling Language™) is the industry-standard graphical language for modeling object-oriented systems. We introduce the UML in the early chapters. Online Chapters 25 and 26 include an optional object-oriented design case study using the UML. We design and fully implement the software for a simple automated teller machine (ATM). We analyze a typical requirements document that specifies the system to be built. We determine the classes needed to implement that system, the attributes the classes need to have, the behaviors the classes need to exhibit and we specify how objects of the classes must interact with one another to meet the system requirements. From the design we produce a complete C++ implementation. Students often report that the case study helps them “tie it all together” and truly understand object orientation.
Understanding how polymorphism works. Chapter 12 contains a detailed diagram and explanation of how C++ typically implements polymorphism, virtual
functions and dynamic binding “under the hood.”
Object-oriented exception handling. We integrate basic exception handling early in the book (Chapter 7). Instructors can easily pull more detailed material forward from Chapter 17, Exception Handling: A Deeper Look.
Custom template-based data structures. We provide a rich multi-chapter treatment of data structures—see the Data Structures module in the chapter dependency chart (Fig. 5).
Three programming paradigms. We discuss structured programming, object-oriented programming and generic programming.
We include a broad range of example programs selected from computer science, information technology, business, simulation, game playing and other topics. The examples are accessible to students in novice-level and intermediate-level C++ courses (Fig. 2).
Examples |
---|
|
Self-Review Exercises and Answers. Extensive self-review exercises and answers are included for self-study.
Interesting, entertaining and challenging exercises. Each chapter concludes with a substantial set of exercises, including simple recall of important terminology and concepts, identifying the errors in code samples, writing individual program statements, writing small portions of C++ classes and member and non-member functions, writing complete programs and implementing major projects. Figure 3 lists a sampling of the book’s exercises, including our Making a Difference exercises, which encourage you to use computers and the Internet to research and work on significant social problems. We hope you’ll approach these exercises with your own values, politics and beliefs.
Exercises |
---|
Airline Reservations System |
Abundant tables, line drawings, UML diagrams, programs and program outputs are included. A sampling of the book’s drawings and diagrams is shown in (Fig. 4).
Drawings and diagrams |
---|
Main text drawings and diagrams |
(Optional) ATM Case Study drawings and diagrams |
C++ How to Program, 10/e is appropriate for most introductory one-and-two-course programming sequences, often called CS1 and CS2. The chart in Fig. 5 shows the dependencies among the chapters to help instructors plan their syllabi. The chart shows the book’s modular organization.
C++ How to Program, 10/e, contains a rich collection of examples. We stress program clarity and concentrate on building well-engineered software.
Live-code approach. The book is loaded with “live-code” examples—most new concepts are presented in complete working C++ applications, followed by one or more executions showing program inputs and outputs.
Rich early coverage of C++ fundamentals. Chapter 2 provides a friendly introduction to C++ programming. We include in Chapters 4 and 5 a clear treatment of control statements and algorithm development.
Syntax coloring. For readability, we syntax color all the C++ code, similar to the way most C++ integrated-development environments and code editors syntax color code. Our coloring conventions are as follows:
comments appear like this
keywords appear like this
constants and literal values appear like this
all other code appears in black
Code highlighting. We place shaded rectangles around the new features in each program.
Using fonts for emphasis. We color the defining occurrence of each key term in bold colored text for easy reference. We emphasize on-screen components in the bold Helvetica font (e.g., the File menu) and C++ program text in the Lucida
font (for example, int x = 5;
).
Objectives. We clearly state the chapter objectives.
Programming tips. We include programming tips to help you focus on key aspects of program development. These tips and practices represent the best we’ve gleaned from a combined eight decades of teaching and industry experience.
The Good Programming Practices call attention to techniques that will help you produce programs that are clearer, more understandable and more maintainable.
Pointing out these Common Programming Errors reduces the likelihood that you’ll make them.
These tips contain suggestions for exposing and removing bugs from your programs; many describe aspects of C++ that prevent bugs from getting into programs in the first place.
These tips highlight opportunities for making your programs run faster or minimizing the amount of memory that they occupy.
These tips help you write code that will run on a variety of platforms.
These tips highlight architectural and design issues that affect the construction of software systems, especially large-scale systems.
Summary Bullets. We present a section-by-section, bullet-list summary of each chapter. Each key term is in bold followed by the page number of the term’s defining occurrence.
Index. For convenient reference, we’ve included an extensive index, with defining occurrences of key terms highlighted with a bold page number.
It’s difficult to build industrial-strength systems that stand up to attacks from viruses, worms, and other forms of “malware.” Today, via the Internet, such attacks can be instantaneous and global in scope. Building security into software from the beginning of the development cycle can greatly reduce vulnerabilities.
The CERT® Coordination Center (www.cert.org
) was created to analyze and respond promptly to attacks. CERT—the Computer Emergency Response Team—is a government-funded organization within the Carnegie Mellon University Software Engineering Institute™. CERT publishes and promotes secure coding standards for various popular programming languages to help software developers implement industrial-strength systems which avoid the programming practices that leave systems open to attacks.
We’d like to thank Robert C. Seacord, an adjunct professor in the Carnegie Mellon University School of Computer Science and former Secure Coding Manager at CERT. Mr. Seacord was a technical reviewer for our book, C How to Program, 7/e, where he scrutinized our C programs from a security standpoint, recommending that we adhere to key guidelines of the CERT C Secure Coding Standard.
We’ve done the same for C++ How to Program, 10/e, adhering to key guidelines of the CERT C++ Secure Coding Standard, which you can find at:
http://www.securecoding.cert.org
We were pleased to discover that we’ve already been recommending many of these coding practices in our books since the early 1990s. We upgraded our code and discussions to conform to these practices, as appropriate for an introductory/intermediate-level textbook. If you’ll be building industrial-strength C++ systems, consider reading Secure Coding in C and C++, Second Edition (Robert Seacord, Addison-Wesley Professional, 2013).
The book’s Companion Website, which is accessible at
http://www.pearsonhighered.com/deitel
(see the inside front cover for your access key) contains the following videos as well as chapters and appendices in searchable PDF format:
VideoNotes—The Companion Website (see the inside front cover for your access key) also includes extensive videos. Watch and listen as co-author Paul Deitel discusses in-depth the key code examples from the book’s core programming-fundamentals and object-oriented-programming chapters.
Chapter 23, Other Topics
Chapter 24, C++11 and C++14 Additional Topics
Chapter 25, ATM Case Study, Part 1: Object-Oriented Design with the UML
Chapter 26, ATM Case Study, Part 2: Implementing an Object-Oriented Design
Appendix F, C Legacy Code Topics
Appendix G, UML: Additional Diagram Types
Appendix H, Using the Visual Studio Debugger
Appendix I, Using the GNU C++ Debugger
Appendix J, Using the Xcode Debugger
Building Your Own Compiler exercise descriptions from Chapter 19 (posted at the Companion Website and at http:/
).
We wrote the code examples in C++ How to Program, 10/e using the following free C++ development tools:
Microsoft’s free Visual Studio Community 2015 edition, which includes Visual C++ and other Microsoft development tools. This runs on Windows and is available for download at
https://www.visualstudio.com/products/visual-studio-community-vs
GNU’s free GNU C++ 5.2.1. GNU C++ is already installed on most Linux systems and can also be installed on Mac OS X and Windows systems. There are many versions of Linux—known as Linux distributions—that use different techniques for performing software upgrades. Check your distribution’s online documentation for information on how to upgrade GNU C++ to the latest version. GNU C++ is available at
http://gcc.gnu.org/install/binaries.html
Apple’s free Xcode, which OS X users can download from the Mac App Store— click the app’s icon in the dock at the bottom of your screen, then search for Xcode in the app store.
The following supplements are available to qualified instructors only through Pearson Education’s Instructor Resource Center (http:/
):
Solutions Manual contains solutions to most of the end-of-chapter exercises. We include Making a Difference exercises, many with solutions. Please do not write to us requesting access to the Pearson Instructor’s Resource Center. Access is restricted to college instructors teaching from the book. Instructors may obtain access only through their Pearson representatives. If you’re not a registered faculty member, contact your Pearson representative or visit
http://www.pearsonhighered.com/educator/replocator/
Solutions are not provided for “project” exercises. Check out our Programming Projects Resource Center for lots of additional exercise and project possibilities.
http://www.deitel.com/ProgrammingProjects
Test Item File of multiple-choice questions.
Customizable PowerPoint® slides containing all the code and figures in the text, plus bulleted items that summarize key points in the text.
MyProgrammingLab™ helps students fully grasp the logic, semantics, and syntax of programming. Through practice exercises and immediate, personalized feedback, MyProgrammingLab improves the programming competence of beginning students who often struggle with the basic concepts and paradigms of popular high-level programming languages.
An optional self-study and homework tool, a MyProgrammingLab course consists of hundreds of small practice problems organized around the structure of this textbook. For students, the system automatically detects errors in the logic and syntax of their code submissions and offers targeted hints that enable students to figure out what went wrong— and why. For instructors, a comprehensive gradebook tracks correct and incorrect answers and stores the code inputted by students for review.
For a full demonstration, to see feedback from instructors and students or to get started using MyProgrammingLab in your course, visit
http://www.myprogramminglab.com
We’d like to thank Barbara Deitel of Deitel & Associates, Inc. for long hours devoted to this project. She painstakingly researched the new capabilities of C++11 and C++14.
We’re fortunate to have worked with the dedicated team of publishing professionals at Pearson Higher Education. We appreciate the guidance, wisdom and energy of Tracy Johnson, Executive Editor, Computer Science. Kristy Alaura did an extraordinary job recruiting the book’s reviewers and managing the review process. Bob Engelhardt did a wonderful job bringing the book to publication.
Finally, thanks to Abbey Deitel, former President of Deitel & Associates, Inc., and a graduate of Carnegie Mellon University’s Tepper School of Management where she received a B.S. in Industrial Management. Abbey managed the business operations of Deitel & Associates, Inc. for 17 years, along the way co-authoring a number of our publications, including the previous C++ How to Program editions’ versions of Chapter 1.
We wish to acknowledge the efforts of our reviewers. Over its ten editions, the book has been scrutinized by academics teaching C++ courses, current and former members of the C++ standards committee and industry experts using C++ to build industrial-strength, high-performance systems. They provided countless suggestions for improving the presentation. Any remaining flaws in the book are our own.
Tenth Edition reviewers: Chris Aburime, Minnesota State Colleges and Universities System; Gašper Ažman, A9.com Search Technologies and Co-Author of C++ Today: The Beast is Back; Danny Kalev, Intel and Former Member of the C++ Standards Committee; Renato Golin, LLVM Tech Lead at Linaro and Co-Owner for the ARM Target in LLVM; Gordon Hogenson, Microsoft, Author of Foundations of C++/CLI: The Visual C++ Language for .NET 3; Jonathan Wakely, Redhat, ISO C++ Committee Secretary; José Antonio González Seco, Parliament of Andalusia; Dean Michael Berris, Google, Maintainer of cpp-netlib and Former ISO C++ Committee Member.
Ninth Edition post-publication academic reviewers: Stefano Basagni, Northeastern University; Amr Elkady, Diablo Valley College; Chris Aburime, Minnesota State Colleges and Universities System.
Other recent edition reviewers: Virginia Bailey (Jackson State University), Ed James-Beckham (Borland), Thomas J. Borrelli (Rochester Institute of Technology), Ed Brey (Kohler Co.), Chris Cox (Adobe Systems), Gregory Dai (eBay), Peter J. DePasquale (The College of New Jersey), John Dibling (SpryWare), Susan Gauch (University of Arkansas), Doug Gregor (Apple, Inc.), Jack Hagemeister (Washington State University), Williams M. Higdon (University of Indiana), Anne B. Horton (Lockheed Martin), Terrell Hull (Logicalis Integration Solutions), Linda M. Krause (Elmhurst College), Wing-Ning Li (University of Arkansas), Dean Mathias (Utah State University), Robert A. McLain (Tide-water Community College), James P. McNellis (Microsoft Corporation), Robert Myers (Florida State University), Gavin Osborne (Saskatchewan Institute of Applied Science and Technology), Amar Raheja (California State Polytechnic University, Pomona), April Reagan (Microsoft), Robert C. Seacord (Secure Coding Manager at SEI/CERT, author of Secure Coding in C and C++), Raymond Stephenson (Microsoft), Dave Topham (Ohlone College), Anthony Williams (author and C++ Standards Committee member) and Chad Willwerth (University Washington, Tacoma).
As you read the book, we’d sincerely appreciate your comments, criticisms and suggestions for improving the text. Please address all correspondence to:
[email protected]
We’ll respond promptly. We enjoyed writing C++ How to Program, Tenth Edition. We hope you enjoy reading it!
Paul Deitel, CEO and Chief Technical Officer of Deitel & Associates, Inc., has over 30 years of experience in computing. He is a graduate of MIT, where he studied Information Technology. He holds the Java Certified Programmer and Java Certified Developer designations and is an Oracle Java Champion. Paul was also named as a Microsoft® Most Valuable Professional (MVP) for C# in 2012–2014. Through Deitel & Associates, Inc., he has delivered hundreds of programming courses worldwide to clients, including Cisco, IBM, Siemens, Sun Microsystems, Dell, Fidelity, NASA at the Kennedy Space Center, the National Severe Storm Laboratory, White Sands Missile Range, Rogue Wave Software, Boeing, SunGard, Nortel Networks, Puma, iRobot, Invensys and many more. He and his co-author, Dr. Harvey Deitel, are the world’s best-selling programming-language textbook/professional book/video authors.
Dr. Harvey Deitel, Chairman and Chief Strategy Officer of Deitel & Associates, Inc., has over 50 years of experience in the computer field. Dr. Deitel earned B.S. and M.S. degrees in Electrical Engineering from MIT and a Ph.D. in Mathematics from Boston University—he studied computing in each of these programs before they spun off Computer Science programs. He has extensive college teaching experience, including earning tenure and serving as the Chairman of the Computer Science Department at Boston College before founding Deitel & Associates, Inc., in 1991 with his son, Paul. The Deitels’ publications have earned international recognition, with translations published in Japanese, German, Russian, Spanish, French, Polish, Italian, Simplified Chinese, Traditional Chinese, Korean, Portuguese, Greek, Urdu and Turkish. Dr. Deitel has delivered hundreds of programming courses to academic, corporate, government and military clients.
Deitel & Associates, Inc., founded by Paul Deitel and Harvey Deitel, is an internationally recognized authoring and corporate training organization, specializing in computer programming languages, object technology, Internet and web software technology, and Android and iOS app development. The company’s clients include academic institutions, many of the world’s largest corporations, government agencies and branches of the military. The company offers instructor-led training courses delivered at client sites worldwide on major programming languages and platforms, including C++, C, Java™, Android app development, iOS app development, Swift™, Visual C#®, Visual Basic®, Internet and web programming and a growing list of additional programming and software-development courses.
Through its 40-year publishing partnership with Prentice Hall/Pearson, Deitel & Associates, Inc., publishes leading-edge programming college textbooks, professional books and LiveLessons video courses. Deitel & Associates, Inc. and the authors can be reached at:
[email protected]
To learn more about Deitel’s corporate training curriculum, visit
http://www.deitel.com/training
To request a proposal for worldwide on-site, instructor-led training at your organization, send an e-mail to [email protected]
.
Individuals wishing to purchase Deitel books can do so via
http://bit.ly/DeitelOnAmazon
Individuals wishing to purchase Deitel LiveLessons video training can do so at:
http://bit.ly/DeitelOnInformit
All Deitel books and LiveLessons videos are also available electronically to Safari Books Online subscribers at:
http://SafariBooksOnline.com
You can get a free 10-day Safari Books Online trial at:
https://www.safaribooksonline.com/register/
Bulk orders by corporations, the government, the military and academic institutions should be placed directly with Pearson. For more information, visit
http://www.informit.com/store/sales.aspx