Tải bản đầy đủ (.pdf) (767 trang)

Sams Teach Yourself C++ in One Hour a Day Seventh Edition doc

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.66 MB, 767 trang )

ptg7987094
www.it-ebooks.info
ptg7987094
in One Hour aDay
C++
SamsTeach Yourself
Siddhartha Rao
800 East 96th Street, Indianapolis, Indiana 46240
Seventh Edition
www.it-ebooks.info
ptg7987094
Sams Teach Yourself C++ in One Hour a Day,
Seventh Edition
Copyright © 2012 by Pearson Education, Inc.
All rights reserved. No part of this book shall be reproduced, stored in a retrieval system,
or transmitted by any means, electronic, mechanical, photocopying, recording, or other-
wise, without written permission from the publisher. No patent liability is assumed with
respect to the use of the information contained herein. Although every precaution has been
taken in the preparation of this book, the publisher and author assume no responsibility for
errors or omissions. Nor is any liability assumed for damages resulting from the use of the
information contained herein.
ISBN-13: 978-0-672-33567-9
ISBN-10: 0-672-33567-0
The Library of Congress Cataloging-in-Publication Data is on file.
Printed in the United States of America
First Printing May 2012
Trademarks
All terms mentioned in this book that are known to be trademarks or service marks have
been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this infor-
mation. Use of a term in this book should not be regarded as affecting the validity of any
trademark or service mark.


Warning and Disclaimer
Every effort has been made to make this book as complete and as accurate as possible,
but no warranty or fitness is implied. The information provided is on an “as is” basis.
The author and the publisher shall have neither liability nor responsibility to any person
or entity with respect to any loss or damages arising from the information contained in
this book.
Bulk Sales
Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk
purchases or special sales. For more information, please contact
U.S. Corporate and Government Sales
1-800-382-3419

For sales outside of the U.S., please contact
International Sales

Acquisitions Editor
Mark Taber
Development Editor
Songlin Qiu
Managing Editor
Sandra Schroeder
Project Editor
Mandie Frank
Copy Editor
Charlotte Kughen
Indexer
Tim Wright
Proofreader
Megan Wade
Technical Editor

Jon Upchurch
Publishing
Coordinator
Vanessa Evans
Designer
Gary Adair
Compositor
Studio Galou, LLC
www.it-ebooks.info
ptg7987094
Contents at a Glance
Introduction 1
PART I: The Basics
1 Getting Started 5
2 The Anatomy of a C++ Program 15
3 Using Variables, Declaring Constants 29
4 Managing Arrays and Strings 57
5 Working with Expressions, Statements, and Operators 77
6 Controlling Program Flow 105
7 Organizing Code with Functions 141
8 Pointers and References Explained 165
PART II: Fundamentals of Object-Oriented C++ Programming
9 Classes and Objects 203
10 Implementing Inheritance 251
11 Polymorphism 283
12 Operator Types and Operator Overloading 311
13 Casting Operators 353
14 An Introduction to Macros and Templates 367
PART III: Learning the Standard Template Library (STL)
15 An Introduction to the Standard Template Library 393

16 The STL String Class 405
17 STL Dynamic Array Classes 423
18 STL list and forward_list 445
19 STL Set Classes 467
20 STL Map Classes 487
PART IV: More STL
21 Understanding Function Objects 511
22 C++11 Lambda Expressions 527
23 STL Algorithms 543
24 Adaptive Containers: Stack and Queue 579
25 Working with Bit Flags Using STL 597
PART V: Advanced C++ Concepts
26 Understanding Smart Pointers 607
27 Using Streams for Input and Output 621
www.it-ebooks.info
ptg7987094
28 Exception Handling 643
29 Going Forward 659
Appendixes
A Working with Numbers: Binary and Hexadecimal 671
B C++ Keywords 677
C Operator Precedence 679
D Answers 681
E ASCII Codes 723
Index 727
www.it-ebooks.info
ptg7987094
Table of Contents
Introduction 1
PART I: The Basics

LESSON 1: Getting Started 5
A Brief History of C++ 6
Connection to C 6
Advantages of C++ 6
Evolution of the C++ Standard . 7
Who Uses Programs Written in C++? . 7
Programming a C++ Application . 7
Steps to Generating an Executable 8
Analyzing Errors and Firefighting. 8
Integrated Development Environments. 8
Programming Your First C++ Application 9
Building and Executing Your First C++ Application . 10
Understanding Compiler Errors . 12
What’s New in C++11 12
Summary. 13
Q&A 13
Workshop 14
LESSON 2: The Anatomy of a C++ Program 15
Part of the Hello World Program 16
Preprocessor Directive #include . 16
The Body of Your Program main() 17
Returning a Value 18
The Concept of Namespaces 19
Comments in C++ Code. 20
Functions in C++ 21
Basic Input Using std::cin and Output Using std::cout . 24
Summary. 26
Q&A 26
Workshop 27
www.it-ebooks.info

ptg7987094
LESSON 3: Using Variables, Declaring Constants 29
What Is a Variable? 30
Memory and Addressing in Brief 30
Declaring Variables to Access and Use Memory 30
Declaring and Initializing Multiple Variables of a Type . 32
Understanding the Scope of a Variable 33
Global Variables . 35
Common Compiler-Supported C++ Variable Types . 36
Using Type bool to Store Boolean Values 37
Using Type char to Store Character Values . 37
The Concept of Signed and Unsigned Integers 38
Signed Integer Types short, int, long, and long long 39
Unsigned Integer Types unsigned short, unsigned int, unsigned
long, and unsigned long long 39
Floating-Point Types float and double 40
Determining the Size of a Variable Using sizeof 40
Using typedef to Substitute a Variable’s Type 44
What Is a Constant? 45
Literal Constants . 45
Declaring Variables as Constants Using const 46
Declaring Constants Using constexpr. 47
Enumerated Constants. 48
Defining Constants Using #define 50
Naming Variables and Constants 51
Keywords You Cannot Use as Variable or Constant Names. 52
Summary. 53
Q&A 53
Workshop 55
LESSON 4: Managing Arrays and Strings 57

What Is an Array? 58
The Need for Arrays. 58
Declaring and Initializing Static Arrays . 59
How Data Is Stored in an Array . 60
Accessing Data Stored in an Array . 61
Modifying Data Stored in an Array . 62
vi
Sams Teach Yourself C++ in One Hour a Day
www.it-ebooks.info
ptg7987094
Multidimensional Arrays 65
Declaring and Initializing Multidimensional Arrays . 65
Accessing Elements in a Multidimensional Array 66
Dynamic Arrays . 68
C-style Strings 70
C++ Strings: Using std::string 72
Summary. 75
Q&A 75
Workshop 76
LESSON 5: Working with Expressions, Statements, and Operators 77
Statements 78
Compound Statements or Blocks 79
Using Operators . 79
The Assignment Operator (=) . 79
Understanding l-values and r-values . 79
Operators to Add (+), Subtract (-), Multiply (*),
Divide (/), and Modulo Divide (%) 80
Operators to Increment (++) and Decrement ( ) 81
To Postfix or to Prefix? 81
Equality Operators (==) and (!=). 84

Relational Operators . 85
Logical Operations NOT, AND, OR, and XOR . 87
Using C++ Logical Operators NOT (!), AND (&&), and OR (||) 88
Bitwise NOT (~), AND (&), OR (|), and XOR (^) Operators . 92
Bitwise Right Shift (>>) and Left Shift (<<) Operators . 94
Compound Assignment Operators 96
Using Operator sizeof to Determine the Memory Occupied by a Variable . 98
Operator Precedence. 99
Summary 101
Q&A 102
Workshop . 102
LESSON 6: Controlling Program Flow 105
Conditional Execution Using if … else 106
Conditional Programming Using if … else . 107
Executing Multiple Statements Conditionally . 109
Contents
vii
www.it-ebooks.info
ptg7987094
Nested if Statements 111
Conditional Processing Using switch-case. 115
Conditional Execution Using Operator (?:) . 118
Getting Code to Execute in Loops . 119
A Rudimentary Loop Using goto 119
The while Loop . 121
The do…while loop 123
The for Loop 125
Modifying Loop Behavior Using continue and break . 128
Loops That Don’t End, that is, Infinite Loops . 129
Controlling Infinite Loops . 130

Programming Nested Loops 133
Using Nested Loops to Walk a Multidimensional Array 134
Using Nested Loops to Calculate Fibonacci Numbers . 136
Summary 137
Q&A 138
Workshop . 138
LESSON 7: Organizing Code with Functions 141
The Need for Functions 142
What Is a Function Prototype? . 143
What Is a Function Definition? . 144
What Is a Function Call, and What Are Arguments? 144
Programming a Function with Multiple Parameters. 145
Programming Functions with No Parameters or No Return Values. 146
Function Parameters with Default Values 147
Recursion—Functions That Invoke Themselves 149
Functions with Multiple Return Statements . 151
Using Functions to Work with Different Forms of Data . 152
Overloading Functions . 152
Passing an Array of Values to a Function 154
Passing Arguments by Reference 156
How Function Calls Are Handled by the Microprocessor . 158
Inline Functions . 159
Lambda Functions 161
Summary 162
viii
Sams Teach Yourself C++ in One Hour a Day
www.it-ebooks.info
ptg7987094
Q&A 163
Workshop . 163

LESSON 8: Pointers and References Explained 165
What Is a Pointer? . 166
Declaring a Pointer . 166
Determining the Address of a Variable Using the Reference Operator (&) . 167
Using Pointers to Store Addresses . 168
Access Pointed Data Using the Dereference Operator (*). 170
What Is the sizeof() of a Pointer? 173
Dynamic Memory Allocation . 175
Using Operators new and delete to Allocate and Release
Memory Dynamically 175
Effect of Incrementing and Decrementing Operators (++ and ) on Pointers . 179
Using const Keyword on Pointers . 181
Passing Pointers to Functions 182
Similarities Between Arrays and Pointers . 184
Common Programming Mistakes When Using Pointers . 186
Memory Leaks 187
When Pointers Don’t Point to Valid Memory Locations 187
Dangling Pointers (Also Called Stray or Wild Pointers) 189
Pointer Programming Best-Practices 189
Checking If Allocation Request Using new Succeeded 191
What Is a Reference? 193
What Makes References Useful? 194
Using Keyword const on References 196
Passing Arguments by Reference to Functions . 196
Summary 198
Q&A 198
Workshop . 200
PART II: Fundamentals of Object-Oriented C++ Programming
LESSON 9: Classes and Objects 203
The Concept of Classes and Objects 204

Declaring a Class 204
Instantiating an Object of a Class 205
Contents
ix
www.it-ebooks.info
ptg7987094
Accessing Members Using the Dot Operator . . 206
Accessing Members Using the Pointer Operator (->). 206
Keywords public and private 208
Abstraction of Data via Keyword private . 210
Constructors 212
Declaring and Implementing a Constructor 212
When and How to Use Constructors . 213
Overloading Constructors . 215
Class Without a Default Constructor 217
Constructor Parameters with Default Values 219
Constructors with Initialization Lists 220
Destructor 222
Declaring and Implementing a Destructor . 222
When and How to Use Destructors 223
Copy Constructor 225
Shallow Copying and Associated Problems 225
Ensuring Deep Copy Using a Copy Constructor 228
Move Constructors Help Improve Performance 233
Different Uses of Constructors and Destructor 235
Class That Does Not Permit Copying 235
Singleton Class That Permits a Single Instance 236
Class That Prohibits Instantiation on the Stack. 239
this Pointer. 241
sizeof() a Class . 242

How struct Differs from class . 244
Declaring a friend of a class 245
Summary 247
Q&A 248
Workshop . 249
LESSON 10: Implementing Inheritance 251
Basics of Inheritance 252
Inheritance and Derivation . 252
C++ Syntax of Derivation 254
Access Specifier Keyword protected 256
Base Class Initialization—Passing Parameters to the Base Class . 258
x
Sams Teach Yourself C++ in One Hour a Day
www.it-ebooks.info
ptg7987094
Derived Class Overriding Base Class’ Methods . 261
Invoking Overridden Methods of a Base Class . . 263
Invoking Methods of a Base Class in a Derived Class . . 264
Derived Class Hiding Base Class’ Methods . 266
Order of Construction 268
Order of Destruction . 268
Private Inheritance 271
Protected Inheritance 273
The Problem of Slicing . 277
Multiple Inheritance. . 277
Summary 281
Q&A. 281
Workshop 281
LESSON 11: Polymorphism 283
Basics of Polymorphism . 284

Need for Polymorphic Behavior 284
Polymorphic Behavior Implemented Using Virtual Functions 286
Need for Virtual Destructors. 288
How Do virtual Functions Work? Understanding the Virtual Function Table . . 292
Abstract Base Classes and Pure Virtual Functions . . 296
Using virtual Inheritance to Solve the Diamond Problem . 299
Virtual Copy Constructors? . 304
Summary 307
Q&A. 307
Workshop 308
LESSON 12: Operator Types and Operator Overloading
311
What Are Operators in C++? 312
Unary Operators 313
Types of Unary Operators 313
Programming a Unary Increment/Decrement Operator . 314
Programming Conversion Operators. . 317
Programming Dereference Operator (*) and Member Selection
Operator (->) . 319
Binary Operators. 323
Types of Binary Operators 324
Contents
xi
www.it-ebooks.info
ptg7987094
Programming Binary Addition (a+b) and Subtraction (a–b) Operators 325
Implementing Addition Assignment (+=) and Subtraction Assignment
(-=) Operators 327
Overloading Equality (==) and Inequality (!=) Operators . 330
Overloading <, >, <=, and >= Operators 332

Overloading Copy Assignment Operator (=) 335
Subscript Operator ([]) . 338
Function Operator () 342
Operators That Cannot Be Overloaded 349
Summary 350
Q&A 351
Workshop . 351
LESSON 13: Casting Operators 353
The Need for Casting . 354
Why C-Style Casts Are Not Popular with Some C++ Programmers . 355
The C++ Casting Operators. 355
Using static_cast 356
Using dynamic_cast and Runtime Type Identification . 357
Using reinterpret_cast 360
Using const_cast 361
Problems with the C++ Casting Operators . 362
Summary 363
Q&A 364
Workshop . 364
LESSON 14: An Introduction to Macros and Templates 367
The Preprocessor and the Compiler 368
Using #define Macros to Define Constants 368
Using Macros for Protection Against Multiple Inclusion . 371
Using #define To Write Macro Functions. 372
Why All the Parentheses? . 374
Using Macro assert to Validate Expressions 375
Advantages and Disadvantages of Using Macro Functions 376
An Introduction to Templates . 378
Template Declaration Syntax 378
The Different Types of Template Declarations . 379

Template Functions. 379
xii
Sams Teach Yourself C++ in One Hour a Day
www.it-ebooks.info
ptg7987094
Templates and Type Safety. 381
Template Classes 381
Template Instantiation and Specialization . 383
Declaring Templates with Multiple Parameters 383
Declaring Templates with Default Parameters . 384
Sample Template class<> HoldsPair 385
Template Classes and static Members . 386
Using Templates in Practical C++ Programming 389
Summary 390
Q&A 390
Workshop . 391
PART III: Learning the Standard Template Library (STL)
LESSON 15: An Introduction to the Standard Template Library 393
STL Containers. 394
Sequential Containers 394
Associative Containers . 395
Choosing the Right Container . 396
STL Iterators 399
STL Algorithms 400
The Interaction Between Containers and Algorithms Using Iterators. 400
STL String Classes 403
Summary 403
Q&A 403
Workshop . 404
LESSON 16: The STL String Class 405

The Need for String Manipulation Classes 406
Working with the STL String Class . 407
Instantiating the STL String and Making Copies 407
Accessing Character Contents of a std::string . 410
Concatenating One String to Another 412
Finding a Character or Substring in a String . 413
Truncating an STL string 415
String Reversal . 417
String Case Conversion . 418
Contents
xiii
www.it-ebooks.info
ptg7987094
Template-Based Implementation of an STL String 420
Summary 420
Q&A 421
Workshop . 421
LESSON 17: STL Dynamic Array Classes 423
The Characteristics of std::vector . 424
Typical Vector Operations . 424
Instantiating a Vector 424
Inserting Elements at the End Using push_back() . 426
Inserting Elements at a Given Position Using insert() 428
Accessing Elements in a Vector Using Array Semantics 431
Accessing Elements in a Vector Using Pointer Semantics . 433
Removing Elements from a Vector . 434
Understanding the Concepts of Size and Capacity 436
The STL deque Class . 438
Summary 441
Q&A 441

Workshop . 442
LESSON 18: STL list and forward_list 445
The Characteristics of a std::list 446
Basic list Operations . 446
Instantiating a std::list Object 446
Inserting Elements at the Front or Back of the List . 448
Inserting at the Middle of the List . 450
Erasing Elements from the List . 453
Reversing and Sorting Elements in a List 455
Reversing Elements Using list::reverse() 455
Sorting Elements 456
Sorting and Removing Elements from a list That Contains Objects of a class 458
Summary 465
Q&A 465
Workshop . 465
xiv
Sams Teach Yourself C++ in One Hour a Day
www.it-ebooks.info
ptg7987094
LESSON 19: STL Set Classes 467
An Introduction to STL Set Classes 468
Basic STL set and multiset Operations 468
Instantiating a std::set Object 469
Inserting Elements in a set or multiset . 471
Finding Elements in an STL set or multiset . 473
Erasing Elements in an STL set or multiset . 475
Pros and Cons of Using STL set and multiset . 480
Summary 484
Q&A 484
Workshop . 485

LESSON 20: STL Map Classes 487
An Introduction to STL Map Classes . 488
Basic std::map and std::multimap Operations . 489
Instantiating a std::map or std::multimap . 489
Inserting Elements in an STL map or multimap 491
Finding Elements in an STL map 494
Finding Elements in an STL multimap . 496
Erasing Elements from an STL map or multimap . 497
Supplying a Custom Sort Predicate. 499
How Hash Tables Work . 504
Using C++11 Hash Tables: unordered_map and unordered_multimap 504
Summary 508
Q&A 509
Workshop . 510
PART IV: More STL
LESSON 21: Understanding Function Objects 511
The Concept of Function Objects and Predicates. 512
Typical Applications of Function Objects. 512
Unary Functions. 512
Unary Predicate . 517
Binary Functions 519
Binary Predicate. 522
Contents
xv
www.it-ebooks.info
ptg7987094
Summary 524
Q&A 524
Workshop . 525
LESSON 22: C++11 Lambda Expressions 527

What Is a Lambda Expression? 528
How to Define a Lambda Expression . 529
Lambda Expression for a Unary Function . 529
Lambda Expression for a Unary Predicate . 531
Lambda Expression with State via Capture Lists [ ] . 532
The Generic Syntax of Lambda Expressions 534
Lambda Expression for a Binary Function . 535
Lambda Expression for a Binary Predicate. 537
Summary 540
Q&A 541
Workshop . 541
LESSON 23: STL Algorithms 543
What Are STL Algorithms? 544
Classification of STL Algorithms . 544
Non-Mutating Algorithms . 544
Mutating Algorithms 545
Usage of STL Algorithms . 547
Finding Elements Given a Value or a Condition 547
Counting Elements Given a Value or a Condition . 550
Searching for an Element or a Range in a Collection 552
Initializing Elements in a Container to a Specific Value 554
Using std::generate() to Initialize Elements to a Value Generated at Runtime. 556
Processing Elements in a Range Using for_each() . 557
Performing Transformations on a Range Using std::transform() . 560
Copy and Remove Operations. 562
Replacing Values and Replacing Element Given a Condition . 565
Sorting and Searching in a Sorted Collection and Erasing Duplicates . 567
Partitioning a Range 570
Inserting Elements in a Sorted Collection . 572
Summary 575

Q&A 575
Workshop . 576
xvi
Sams Teach Yourself C++ in One Hour a Day
www.it-ebooks.info
ptg7987094
LESSON 24: Adaptive Containers: Stack and Queue 579
The Behavioral Characteristics of Stacks and Queues. 580
Stacks 580
Queues . 580
Using the STL stack Class . 581
Instantiating the Stack 581
Stack Member Functions 582
Insertion and Removal at Top Using push() and pop() . 583
Using the STL queue Class . 585
Instantiating the Queue . 585
Member Functions of a queue 586
Insertion at End and Removal at the Beginning of queue via push()
and pop() 587
Using the STL Priority Queue . 589
Instantiating the priority_queue Class 589
Member Functions of priority_queue 590
Insertion at the End and Removal at the Beginning of priority_queue via
push() and pop(). 591
Summary 594
Q&A 594
Workshop . 594
LESSON 25: Working with Bit Flags Using STL 597
The bitset Class 598
Instantiating the std::bitset . 598

Using std::bitset and Its Members. 599
Useful Operators Featured in std::bitset 599
std::bitset Member Methods 600
The vector<bool> . 603
Instantiating vector<bool> . 603
vector<bool> Functions and Operators . 604
Summary 605
Q&A 605
Workshop . 606
Contents
xvii
www.it-ebooks.info
ptg7987094
PART V: Advanced C++ Concepts
LESSON 26: Understanding Smart Pointers 607
What Are Smart Pointers?. 608
The Problem with Using Conventional (Raw) Pointers 608
How Do Smart Pointers Help? . 608
How Are Smart Pointers Implemented? 609
Types of Smart Pointers 610
Deep Copy . 611
Copy on Write Mechanism. 613
Reference-Counted Smart Pointers . 613
Reference-Linked Smart Pointers 614
Destructive Copy 614
Using the std::unique_ptr 617
Popular Smart Pointer Libraries 618
Summary 619
Q&A 619
Workshop . 620

LESSON 27: Using Streams for Input and Output 621
Concept of Streams 622
Important C++ Stream Classes and Objects 623
Using std::cout for Writing Formatted Data to Console . 624
Changing Display Number Formats Using std::cout 624
Aligning Text and Setting Field Width Using std::cout 627
Using std::cin for Input 628
Using std::cin for Input into a Plain Old Data Type. 628
Using std::cin::get for Input into C-Style char Buffer . 629
Using std::cin for Input into a std::string 630
Using std::fstream for File Handling 632
Opening and Closing a File Using open() and close() . 632
Creating and Writing a Text File Using open() and operator<< 634
Reading a Text File Using open() and operator>> 635
Writing to and Reading from a Binary File 636
Using std::stringstream for String Conversions 638
Summary 640
Q&A 640
Workshop . 641
xviii
Sams Teach Yourself C++ in One Hour a Day
www.it-ebooks.info
ptg7987094
LESSON 28: Exception Handling 643
What Is an Exception? . 644
What Causes Exceptions? 644
Implementing Exception Safety via try and catch . 645
Using catch( ) to Handle All Exceptions . 645
Catching Exception of a Type 647
Throwing Exception of a Type Using throw 648

How Exception Handling Works . 650
Class std::exception . 652
You r C ustom Excepti on Class Derived fro m std::exception . 653
Summary 655
Q&A 656
Workshop . 656
LESSON 29: Going Forward 659
What’s Different in Today’s Processors? . 660
How to Better Use Multiple Cores 661
What Is a Thread? . 661
Why Program Multithreaded Applications? . 662
How Can Threads Transact Data? . 663
Using Mutexes and Semaphores to Synchronize Threads . 664
Problems Caused by Multithreading. 664
Writing Great C++ Code . 665
Learning C++ Doesn’t Stop Here! . 667
Online Documentation 667
Communities for Guidance and Help 668
Summary 668
Q&A 668
Workshop . 669
Appendixes
APPENDIX A: Working with Numbers: Binary and Hexadecimal 671
Decimal Numeral System . 672
Binary Numeral System 672
Why Do Computers Use Binary? . 673
Contents
xix
www.it-ebooks.info
ptg7987094

What Are Bits and Bytes? 673
How Many Bytes Make a Kilobyte?. 674
Hexadecimal Numeral System . 674
Why Do We Need Hexadecimal? . 674
Converting to a Different Base. 675
The Generic Conversion Process 675
Converting Decimal to Binary. 675
Converting Decimal to Hexadecimal 676
APPENDIX B: C++ Keywords 677
APPENDIX C: Operator Precedence 679
APPENDIX D: Answers 681
APPENDIX E: ASCII Codes 723
ASCII Table of Printable Characters 724
Index 727
xx
Sams Teach Yourself C++ in One Hour a Day
www.it-ebooks.info
ptg7987094
About the Author
Siddhartha Rao is a technologist at SAP AG, the world’s leading supplier of enterprise
software. As the head of SAP Product Security India, his primary responsibilities include
hiring expert talent in the area of product security as well as defining development best
practices that keeps SAP software globally competitive. Awarded Most Valuable
Professional by Microsoft for Visual Studio–Visual C++, he is convinced that C++11
will help you program faster, simpler, and more efficient C++ applications.
Siddhartha also loves traveling and discovering new cultures given an opportunity to. For
instance, parts of this book have been composed facing the Atlantic Ocean at a quaint
village called Plogoff in Brittany, France—one of the four countries this book was
authored in. He looks forward to your feedback on this global effort!
Dedication

This book is dedicated to my lovely parents and my wonderful sister for being
there when I have needed them the most.
Acknowledgments
I am deeply indebted to my friends who cooked and baked for me while I burned the
midnight oil working on this project. I am grateful to the editorial staff for their very
professional engagement and the wonderful job in getting this book to your shelf!
www.it-ebooks.info
ptg7987094
We Want to Hear from You!
As the reader of this book, you are our most important critic and commentator. We value
your opinion and want to know what we’re doing right, what we could do better, what
areas you’d like to see us publish in, and any other words of wisdom you’re willing to
pass our way.
You can e mai l or w rit e dir ect ly t o let us kn ow wha t you did o r di dn’t l ike a bou t thi s
book—as well as what we can do to make our books stronger.
Please note that we cannot help you with technical problems related to the topic of this
book, and that due to the high volume of mail we receive, we might not be able to reply
to every message.
When you write, please be sure to include this book’s title and author as well as your
name and phone number or email address.
E-mail:
Mail: Reader Feedback
Sams Publishing
800 East 96th Street
Indianapolis, IN 46240 USA
Reader Services
Visit our website and register this book at informit.com/register for convenient access to
any updates, downloads, or errata that might be available for this book.
www.it-ebooks.info
ptg7987094

Introduction
2011 was a special year for C++. With the ratification of the new standard, C++11
empowers you to write better code using new keywords and constructs that increase your
programming efficiency. This book helps you learn C++11 in tiny steps. It has been
thoughtfully divided into lessons that teach you the fundamentals of this object-oriented
programming language from a practical point of view. Depending on your proficiency
level, you will be able to master C++11 one hour at a time.
Learning C++ by doing is the best way—so try the rich variety of code samples in this
book hands-on and help yourself improve your programming proficiency. These code
snippets have been tested using the latest versions of the available compilers at the time
of writing, namely the Microsoft Visual C++ 2010 compiler for C++ and GNU’s C++
compiler version 4.6, which both offer a rich coverage of C++11 features.
Who Should Read This Book?
The book starts with the very basics of C++. All that is needed is a desire to learn this
language and curiosity to understand how stuff works. An existing knowledge of C++
programming can be an advantage but is not a prerequisite. This is also a book you might
like to refer to if you already know C++ but want to learn additions that have been made
to the language in C++11. If you are a professional programmer, Part III, “Learning the
Standard Template Library (STL),” is bound to help you create better, more practical
C++11 applications.
Organization of This Book
Depending on your current proficiency levels with C++, you can choose the section you
would like to start with. This book has been organized into five parts:
n
Part I, “The Basics,” gets you started with writing simple C++ applications. In
doing so, it introduces you to the keywords that you most frequently see in C++
code of a variable without compromising on type safety.
n
Part II, “Fundamentals of Object-Oriented C++ Programming,” teaches you the
concept of classes. You learn how C++ supports the important object-oriented pro-

gramming principles of encapsulation, abstraction, inheritance, and polymorphism.
www.it-ebooks.info
ptg7987094
Lesson 9, “Classes and Objects,” teaches you the new C++11 concept of move
constructor followed by the move assignment operator in Lesson 12, “Operator
Types and Operator Overloading.” These performance features help reduce
unwanted and unnecessary copy steps, boosting the performance of your applica-
tion. Lesson 14, “An Introduction to Macros and Templates,” is your stepping stone
into writing powerful generic C++ code.
n
Part III, “Learning the Standard Template Library (STL),” helps you write efficient
and practical C++ code using the STL string class and containers. You learn how
std::string makes simple string concatenation operations safe and easy and how
you don’t need to use C-style char* strings anymore. You will be able to use STL
dynamic arrays and linked lists instead of programming your own.
n
Part IV, “More STL,” focuses on algorithms. You learn to use sort on containers
such as vector via iterators. In this part, you find out how C++11 keyword auto
has made a significant reduction to the length of your iterator declarations. Lesson
22, “C++11 Lambda Expressions,” presents a powerful new feature that results in
significant code reduction when you use STL algorithms.
n
Part V, “Advanced C++ Concepts,” explains language capabilities such as smart
pointers and exception-handling, which are not a must in a C++ application but
help make a significant contribution toward increasing its stability and quality. This
part ends with a note on best practices in writing good C++11 applications.
Conventions Used in This Book
Within the lessons, you find the following elements that provide additional information:
2
Sams Teach Yourself C++ in One Hour a Day

These boxes provide additional information related to material you
read.
C++11
These boxes highlight features new to C++11. You may need to use the newer versions
of the available compilers to use these language capabilities.
NOTE
www.it-ebooks.info

×