29,99 €
Get ready for C++20 with all you need to know for complete mastery! Your comprehensive and updated guide to one of the world's most popular programming languages is here! Whether you're a novice or expert, you'll find what you need to get going with the latest features of C++20. The workhorse of programming languages, C++ gives you the utmost control of data usage and interface and resource allocation. If your job involves data, proficiency in C++ means you're indispensable! This edition gives you 7 books in 1 for total C++ mastery. Inside, internationally renowned expert John Paul Mueller takes you from the fundamentals of working with objects and classes to writing applications that use paradigms not normally associated with C++, such as those used for functional programming strategies. The book also includes online resources such as source code. You discover how to use a C++ GNU compiler to build applications and even how to use your mobile device for coding. * Conquer advanced programming and troubleshooting * Streamline your code with lambda expressions * Use C++ where you need it: for gaming, enterprise applications, and Web services * Uncover object secrets including the use of design patterns * Discover how to use functional programming techniques to make code concise and easy to read If you want to be your organization's C++ guru, C++ All-In-One for Dummies is where it's at!
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 1236
Veröffentlichungsjahr: 2020
C++ All-in-One For Dummies®, 4th Edition
Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com
Copyright © 2021 by John Wiley & Sons, Inc., Hoboken, New Jersey
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the Publisher. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Trademarks: Wiley, For Dummies, the Dummies Man logo, Dummies.com, Making Everything Easier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and may not be used without written permission. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. For technical support, please visit https://hub.wiley.com/community/support/dummies.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2020949804
ISBN: 978-1-119-60174-6
ISBN 978-1-119-60175-3 (ebk); ISBN 978-1-119-60173-9 (ebk)
Cover
Title Page
Copyright
Introduction
About This Book
Foolish Assumptions
Icons Used in This Book
Beyond the Book
Where to Go from Here
Book 1: Getting Started with C++
Chapter 1: Configuring Your Desktop System
Obtaining a Copy of C++ 20
Obtaining Code::Blocks
Installing Code::Blocks
Touring the Essential Code::Blocks Features
Using Other IDEs
Chapter 2: Configuring Your Mobile System
Obtaining CppDroid
Considering Other Alternatives
Touring the Essential CppDroid Features
Obtaining CppDroid Help
Chapter 3: Creating Your First C++ Application
Code::Blocks Creating a Project
Typing the Code
Starting with Main
Showing Information
Let Your Application Run Away
Chapter 4: Storing Data in C++
Putting Your Data Places: Variables
Manipulating Integer Variables
Characters
Strings
Making Decisions Using Conditional Operators
Telling the Truth with Boolean Variables
Reading from the Console
Chapter 5: Directing the Application Flow
Doing This or Doing That
Evaluating Conditions in C++
Including Evaluations in C++ Conditional Statements
Repeating Actions with Statements That Loop
Looping for
Looping while
Doing while
Breaking and continuing
Nesting loops
Chapter 6: Dividing Your Work with Functions
Dividing Your Work
Calling a Function
Writing Your Own Functions
Improving On the Basic Function
Calling All String Functions
Understanding main()
Chapter 7: Splitting Up Source Code Files
Creating Multiple Source Files
Sharing with Header Files
Sharing Variables among Source Files
Using the Mysterious Header Wrappers
Chapter 8: Referring to Your Data Through Pointers
Understanding the Changes in Pointers for C++ 20
Heaping and Stacking the Variables
Creating New Raw Pointers
Freeing Raw Pointers
Working with Smart Pointers
Passing Pointer Variables to Functions
Returning Pointer Variables from Functions
Book 2: Understanding Objects and Classes
Chapter 1: Working with Classes
Understanding Objects and Classes
Working with a Class
Starting and Ending with Constructors and Destructors
Building Hierarchies of Classes
Creating and Using Object Aliases
Chapter 2: Using Advanced C++ Features
Filling Your Code with Comments
Converting Types
Reading from the Console
Understanding Preprocessor Directives
Using Constants
Using Switch Statements
Supercharging enums with Classes
Working with Random Numbers
Storing Data in Arrays
Chapter 3: Planning and Building Objects
Recognizing Objects
Encapsulating Objects
Building Hierarchies
Chapter 4: Building with Design Patterns
Delving Into Pattern History
Introducing a Simple Pattern: the Singleton
Watching an Instance with an Observer
Mediating with a Pattern
Book 3: Understanding Functional Programming
Chapter 1: Considering Functional Programming
Understanding How Functional Programming Differs
Defining an Impure Language
Seeing Data as Immutable
Considering the Effects of State
Eliminating Side Effects
Understanding the Role of auto
Passing Functions to Functions
Using Lambda Expressions for Implementation
Chapter 2: Working with Lambda Expressions
Creating More Readable and Concise C++ Code
Defining the Essential Lambda Expression
Developing with Lambda Expressions
Chapter 3: Advanced Lambda Expressions
Considering the C++ 20 Lambda Extensions
Working in Unevaluated Contexts
Using Assignable Stateless Lambda Expressions
Dealing with Pack Expansions
Book 4: Fixing Problems
Chapter 1: Dealing with Bugs
It’s Not a Bug. It’s a Feature!
Make Your Application Features Look Like Features
Anticipating (Almost) Everything
Avoiding Mistakes, Plain and Simple
Chapter 2: Debugging an Application
Programming with Debuggers
Debugging with Different Tools
Debugging a Code::Blocks Application with Command-Line Arguments
Chapter 3: Stopping and Inspecting Your Code
Setting and Disabling Breakpoints
Watching, Inspecting, and Changing Variables
Chapter 4: Traveling About the Stack
Stacking Your Data
Debugging with Advanced Features
Book 5: Advanced Programming
Chapter 1: Working with Arrays, Pointers, and References
Building Up Arrays
Pointing with Pointers
Referring to References
Chapter 2: Creating Data Structures
Working with Data
Structuring Your Data
Naming Your Space
Chapter 3: Constructors, Destructors, and Exceptions
Constructing and Destructing Objects
Programming the Exceptions to the Rule
Chapter 4: Advanced Class Usage
Inherently Inheriting Correctly
Using Classes and Types within Classes
Chapter 5: Creating Classes with Templates
Templatizing a Class
Going Beyond the Basics
Parameterizing a Template
Typedefing a Template
Deriving Templates
Templatizing a Function
Chapter 6: Programming with the Standard Library
Architecting the Standard Library
Containing Your Classes
The Great Container Showdown
Copying Containers
Creating and Using Dynamic Arrays
Working with Unordered Data
Working with Ranges
Book 6: Reading and Writing Files
Chapter 1: Filing Information with the Streams Library
Seeing a Need for Streams
Programming with the Streams Library
Handling Errors When Opening a File
Flagging the ios Flags
Chapter 2: Writing with Output Streams
Inserting with the << Operator
Formatting Your Output
Chapter 3: Reading with Input Streams
Extracting with Operators
Encountering the End of File
Reading Various Types
Chapter 4: Building Directories and Contents
Manipulating Directories
Getting the Contents of a Directory
Copying Files
Moving and Renaming Files and Directories
Chapter 5: Streaming Your Own Classes
Streaming a Class for Text Formatting
Manipulating a Stream
Book 7: Advanced Standard Library Usage
Chapter 1: Exploring the Standard Library Further
Considering the Standard Library Categories
Parsing Strings Using a Hash
Obtaining Information Using a Random Access Iterator
Locating Values Using the Find Algorithm
Using the Random Number Generator
Working with Temporary Buffers
Chapter 2: Working with User-Defined Literals (UDLs)
Understanding the Need for UDLs
Working with the UDLs in the Standard Library
Creating Your Own UDLs
Chapter 3: Building Original Templates
Deciding When to Create a Template
Defining the Elements of a Good Template
Creating a Basic Math Template
Building a Structure Template
Developing a Class Template
Considering Template Specialization
Creating a Template Library
Using Your Template Library
Chapter 4: Investigating Boost
Considering the Standard Library Alternative
Understanding Boost
Obtaining and Installing Boost for Code::Blocks
Creating the Boost Tools
Using Boost.Build
Using Inspect
Understanding BoostBook
Using QuickBook
Using bcp
Using Wave
Building Your First Boost Application Using Date Time
Chapter 5: Boosting up a Step
Parsing Strings Using RegEx
Breaking Strings into Tokens Using Tokenizer
Performing Numeric Conversion
Creating Improved Loops Using Foreach
Accessing the Operating System Using Filesystem
Index
About the Authors
Connect with Dummies
End User License Agreement
Book 1 Chapter 2
TABLE 2-1: CppDroid Features
Book 1 Chapter 3
TABLE 3-1 Navigation and Edit Commands
TABLE 3-2 Math Symbols
TABLE 3-3 Keyboard Shortcuts for Compiling and Running
Book 1 Chapter 4
TABLE 4-1 A Variable Has Three Aspects
TABLE 4-2 Examples of Bad Variable Names
TABLE 4-3 Doing Things with Addition
Book 1 Chapter 5
TABLE 5-1 Evaluating Numerical Conditions
TABLE 5-2 Choosing Your Loops
Book 2 Chapter 1
TABLE 1-1 Specifying Property Values for Instances of Class Pen
TABLE 1-2 Steps to Using Objects
Book 3 Chapter 2
TABLE 2-1 Elements of a Lambda Expression
Book 5 Chapter 2
TABLE 2-1: ANSI C++ Character Types
Book 6 Chapter 2
TABLE 2-1 ios_base Formatting Flags
TABLE 2-2 Using ANSI-Standard Manipulators and Demanipulators
Book 7 Chapter 2
TABLE 2-1 Standard Prefixes and Suffixes
Book 1 Chapter 1
FIGURE 1-1: The wizard asks you to select the configuration options to use.
FIGURE 1-2: The Ubuntu Software Center contains a list of the most popular soft...
FIGURE 1-3: The Developer Tools category contains an entry for Code::Blocks.
FIGURE 1-4: It's possible to obtain additional information about Code::Blocks i...
FIGURE 1-5: Associate Code::Blocks with your C++ files to make it easier to man...
FIGURE 1-6: Code::Blocks provides a tips dialog box that contains helpful infor...
FIGURE 1-7: Save your changes to disk.
FIGURE 1-8: Each example has a
.cbp
file associated with it that opens the exam...
FIGURE 1-9: Use the Start Here window to start a new session.
FIGURE 1-10: The Management window helps you manage your Code::Blocks projects.
FIGURE 1-11: Using the Logs & Others window to understand how your application ...
FIGURE 1-12: Set Code::Blocks to use the GCC compiler to run the examples in th...
Book 1 Chapter 2
FIGURE 2-1: Locating CppDroid in the Google Play Store.
FIGURE 2-2: Loading the CppDroid libraries for offline use.
FIGURE 2-3: Web-based IDEs tend to provide a very simple interface.
FIGURE 2-4: Accessing the basic CppDroid user interface features.
FIGURE 2-5: Use the menu to locate the CppDroid features and options.
FIGURE 2-6: Loading an example provides a quick way to see code in action.
FIGURE 2-7: Give permission to access your Google Drive.
FIGURE 2-8: The file is available for use with your local copy of CppDroid.
FIGURE 2-9: Define a new local project.
FIGURE 2-10: The list of actions in CppDroid is somewhat limited.
FIGURE 2-11: A list of Help sources for CppDroid.
FIGURE 2-12: The developer uses blog posts to help you find bug fixes.
FIGURE 2-13: Use an example to see how the static analysis feature works.
FIGURE 2-14: The tutorials take you through basic processes within CppDroid.
Book 1 Chapter 3
FIGURE 3-1: The New from Template dialog box lets you select a new project type...
FIGURE 3-2: Provide the name of your project for Code::Blocks.
FIGURE 3-3: Tell Code::Blocks where to place the Debug and Release versions of ...
FIGURE 3-4: Use the Code::Blocks IDE to interact with your project.
FIGURE 3-5: Execute your first application.
FIGURE 3-6: Code::Blocks tells you about errors in your application.
FIGURE 3-7: Configure the editor to use automatic indents.
FIGURE 3-8: The computer likes to use orders of operation.
FIGURE 3-9: A programmer calculator comes in handy when working with numbers.
FIGURE 3-10: You can see how overruns occur by doing the math.
Book 1 Chapter 5
FIGURE 5-1: Configure GCC to use the C++ 17 standard.
Book 1 Chapter 6
FIGURE 6-1: Dividing a process into a hierarchy.
FIGURE 6-2: You can think of a function as a machine.
FIGURE 6-3: Command-line apps often have switches and arguments.
Book 1 Chapter 7
FIGURE 7-1: The New from Template dialog box lets you select a new file type.
FIGURE 7-2: Provide the file information required by the wizard.
FIGURE 7-3: The Management window displays the files used to compile the projec...
FIGURE 7-4: Supply a project name for your new application.
FIGURE 7-5: The current directory doesn’t contain any code files.
FIGURE 7-6: Select the builds where the files are used.
FIGURE 7-7: The new project now contains references to the selected files.
FIGURE 7-8: Remove the references you no longer need.
Book 1 Chapter 8
FIGURE 8-1: The two stack frames used for the example code.
Book 2 Chapter 2
FIGURE 2-1: The formatted output shows the difference between truncating and ro...
FIGURE 2-2: Provide the compiler options you want to use to change the applicat...
Book 2 Chapter 3
FIGURE 3-1: The outer object in this picture is a mailbox container.
FIGURE 3-2: The smaller inner objects in this picture are the mailboxes.
FIGURE 3-3: You can draw a class by using a box divided into three horizontal s...
FIGURE 3-4: The arrows in this UML diagram point toward the base class.
Book 2 Chapter 4
FIGURE 4-1: A model of the hierarchy between classes.
FIGURE 4-2: A mediator certainly cleans things up!
Book 3 Chapter 1
FIGURE 1-1: Seeing errors generated as the result of immutability in a structur...
Book 4 Chapter 2
FIGURE 2-1: The main Code::Blocks window shows your source code.
FIGURE 2-2: Completing the run shows the application results.
FIGURE 2-3: Be sure to check the output to ensure that it’s what you expected.
FIGURE 2-4: The debugger shows the beginning and end of code blocks.
FIGURE 2-5: The Disassembly window displays the assembly language version of yo...
Book 4 Chapter 3
FIGURE 3-1: Code::Blocks displays any breakpoints you set using a red octagon.
FIGURE 3-2: Debug mode tells Code::Blocks to stop execution when it reaches the...
FIGURE 3-3: Use the Edit Breakpoint dialog box to enable and disable breakpoint...
FIGURE 3-4: Disabled breakpoints don’t stop application execution.
FIGURE 3-5: Use the Breakpoints window to access a number of breakpoints at one...
FIGURE 3-6: The Watches window shows the value of variables and objects.
FIGURE 3-7: Assigning a value to
i
changes its value in the Watches window.
FIGURE 3-8: Adding a watch to the window presents additional information.
Book 4 Chapter 4
FIGURE 4-1: The Call Stack window shows the function calls that led up to the c...
FIGURE 4-2: The Disassembly window shows the assembly code that results from th...
FIGURE 4-3: This Disassembly window shows the
CountCarSeats()
function code.
FIGURE 4-4: Small C++ code changes can result in large assembly-code changes.
FIGURE 4-5: Viewing the CPU registers can give you insight into how code intera...
Book 5 Chapter 1
FIGURE 1-1: Use the Select Target dialog box to add program arguments.
Book 5 Chapter 4
FIGURE 4-1: Using diamond inheritance can be hard.
Book 6 Chapter 1
FIGURE 1-1: Working with streams requires use of the appropriate headers and co...
Book 7 Chapter 3
FIGURE 3-1: Provide a description of your project for Code::Blocks.
FIGURE 3-2: Provide a description of your static library for Code::Blocks.
FIGURE 3-3: Change the compiler settings to meet your project needs.
FIGURE 3-4: Add new files using the New from Template dialog box.
FIGURE 3-5: Define the header requirements.
Book 7 Chapter 4
FIGURE 4-1: Use the Compiler Settings dialog box to configure Code::Blocks to u...
FIGURE 4-2: Add appropriate search directories for Boost header and library fil...
FIGURE 4-3: The Search Directories tab will display any compiler, linker, or re...
FIGURE 4-4: The example requires the use of a special library.
FIGURE 4-5: The needed file appears in the Link Libraries list.
FIGURE 4-6: The example displays the result of the search.
FIGURE 4-7: Inspect normally outputs its reports as HTML.
FIGURE 4-8: The bcp utility can output some nice-looking reports about Boost mo...
FIGURE 4-9: Select the Boost library directory.
FIGURE 4-10: Make sure you set the environment to use Boost.
Book 7 Chapter 5
FIGURE 5-1: Select the library you want to add.
FIGURE 5-2: Add the library to the application.
FIGURE 5-3: Add appropriate search directories for Boost header and library fil...
FIGURE 5-4: The search location for any compiler, linker, or resource compiler.
FIGURE 5-5: Using the Filesystem library requires the System library as well.
Cover
Title Page
Copyright
Table of Contents
Begin Reading
Index
About the Authors
i
ii
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
893
894
895
There are many general-purpose programming languages today, but few can claim to be the language of the millennium. C++ can make that claim, and for good reason:
It’s powerful. You can write almost any program in it.
It’s fast, and it’s fully compiled
.
That’s a good thing.
It’s easy to use — if you have this book.
It’s object oriented. If you’re not sure what that is, don’t worry. You can find out about it by reading this very book you’re holding.
It supports functional programming techniques, which makes modeling math problems considerably easier and makes parallel processing easier. This book covers functional programming techniques, too.
It’s portable. Versions are available for nearly every computer.
It’s standardized. The American National Standards Institute (ANSI) and the International Standards Organization (ISO) both approve an official version.
It’s continually updated to meet the changing challenges of the computer community.
It’s popular. More people are using C++ because so many other people use it.
Sure, some people criticize C++. But most of these people don’t truly understand C++ or are just having a bad day. Or both.
This book is a hands-on, roll-up-your-sleeves experience that gives you the opportunity to truly learn C++. This edition starts out by helping you get a great C++ installation in place. A lot of readers wrote to tell me that they simply couldn’t get C++ to work for them, and I listened by adding configuration instructions in Book 1, Chapter 1. You can find instructions for working with the Mac, Linux, and Windows throughout the book. The examples are also tested to work on all three platforms.
C++ All-in-One For Dummies, 4th Edition, is devoted to working with C++ wherever you want to use it. Book 1, Chapter 2 even includes techniques for writing C++ code on your mobile device, although writing a complex application on your smartphone would be understandably difficult because of the small device size.
At the very beginning, I start you out from square one. I don’t assume any programming experience whatsoever. Everybody has to start somewhere. You can start here. Not to brag, but you are in the hands of a highly successful C++ developer who has shown thousands of people how to program, many of whom also started out from square one.
You already know C++? This book is great for you, too, because although I start discussing C++ from the beginning, I cover the important aspects of the language in depth. Even if you’ve used C++ in the past, this book gets you up to speed with the latest in C++ 14 and above innovations, including C++ 20 additions. Plus, this edition of the book focuses on all the latest programming strategies while removing some of the less used functionality of the past.
If you’re interested in using the time-tested Object Oriented Programming (OOP) techniques that C++ developers have used for years, then Book 2 is where you want to look. You start with a view of classes, but eventually move into more advanced topics, including the use of programming patterns in Book 2 Chapter 4.
One of the most exciting additions to this edition is the use of functional programming techniques, which you can find in Book 3. Functional programming has become extremely popular because it makes modeling math problems significantly easier, and many people use functional programming techniques to solve modern data science problems. More important, functional programming can be a lot easier than earlier programming paradigms.
Every application out there has a bug or two. If you doubt this statement, just try to find one that is bug free—you won’t. Book 4 includes all sorts of techniques you can use to make your application as bug free as possible before it leaves your machine and then help you find the bugs that others graciously point out later.
Book 5 is all about moving you from generalized programming strategies into the advanced strategies used by modern developers. It starts with a look at standardized structures for working with classes in a safe manner. The minibook takes you through
Simple structures, such as arrays
More advanced data management
The use of constructors, destructors, and exceptions
Templatized programming
Use of the Standard Library (originally called the Standard Template Library or STL).
Everyone needs to work with files at some point. You use local, network, and Internet files today on a regular basis. Book 6 is all about working with files in various ways. This book includes topics on working with data streams as well.
The Standard Library is immense and there are entire books written about its use. C++ All-in-One For Dummies, 4th Edition, focuses on providing you with a really good overview that you can use to drill down into more detailed topics later. Besides looking at the Standard Library in more detail, you discover how to work with User Defined Literals (UDLs) and how to create your own templates. This book also delves into the Boost library, which is the library that has added more to Standard Library than just about any other source. Check out Book 7, Chapters 4 and 5 to learn about Boost. If you use C++ and don’t use Boost, you’re really missing out!
C++ is standardized, and you can use the information in this book on many different platforms. I wrote the samples using Mac OS X, SUSE Linux (some of the beta readers used other flavors of Linux), and Windows systems (with some testing on my ASUS tablet as well). In order to make this happen, I used a compiler called Code::Blocks that runs on almost every computer (Windows, Linux, and Macintosh) and CppDroid for my tablet. It doesn’t matter which device you’re using!
To make absorbing the concepts easy, this book uses the following conventions:
Text that you’re meant to type just as it appears in the book is in
bold
. The exception is when you’re working through a step list: Because each step is bold, the text to type is not bold.
Web addresses and programming code appear in
monofont
. If you’re reading a digital version of this book on a device connected to the Internet, you can click or tap the web address to visit that website, like this:
https://www.dummies.com
.
When you need to type command sequences, you see them separated by a special arrow, like this: File⇒ New File. In this example, you go to the File menu first and then select the New File entry on that menu.
When you see words in
italics
as part of a typing sequence, you need to replace that value with something that works for you. For example, if you see “Type
Your Name
and press Enter,” you need to replace
Your Name
with your actual name.
This book is designed for novice and professional alike. You can either read this book from cover to cover, or you can look up topics and treat the book as a reference guide — whichever works best for you. Keep it on your shelf, and have it ready to grab when you need to look something up. However, I’ve made some assumptions about your level of knowledge when I put the book together. The most important of these assumptions is that you already know how to use your device and work with the operating system that supports it. You also need to know how to perform tasks like downloading files and installing applications. A familiarity with the Internet is also required, and you need to know how to interact with it moderately well to locate the resources you need to work with the book. Finally, you must know how to work with archives, such as the ZIP file format.
As you read this book, you see icons in the margins that indicate material of interest (or not, as the case may be). This section briefly describes each icon in this book.
Tips are nice because they help you save time or perform some task without a lot of extra work. The tips in this book are time-saving techniques or pointers to resources that you should try so that you can get the maximum benefit from C++. Most important, many of these tips will help you make sense of the overwhelming quantity of libraries and tools that C++ developers have created over the years.
I don’t want to sound like an angry parent or some kind of maniac, but you should avoid doing anything that’s marked with a Warning icon. Otherwise, you might find that your application fails to work as expected, you get incorrect answers from seemingly bulletproof code, or (in the worst-case scenario) you lose data. Given where C++ appears, you might also send the next rocket off to Mars prematurely, make someone’s thermostat misbehave, or cause nationwide power outages. Really, warnings are for everyone!
Whenever you see this icon, think advanced tip or technique. You might find these tidbits of useful information just too boring for words, or they could contain the solution you need to get a program running. Skip these bits of information whenever you like.
If you don’t get anything else out of a particular chapter or section, remember the material marked by this icon. This text usually contains an essential process or a bit of information that you must know to work with C++, or to perform development tasks successfully.
If you want to email me, please do! Make sure you send your book-specific requests to:
I get a lot of email from readers, so sometimes it takes me a while to answer. I try very hard to answer every book-specific question I receive, though, so I highly recommend contacting me with your questions. I want to ensure that your book experience is the best one possible. The blog category at http://blog.johnmuellerbooks.com/categories/263/c-all-in-one-for-dummies.aspx contains a wealth of additional information about this book. You can check out the website at http://www.johnmuellerbooks.com/.
This book isn’t the end of your C++ programming experience — it’s really just the beginning. I provide online content to make this book more flexible and better able to meet your needs. That way, as I receive email from you, I can address questions and tell you how updates to either Code::Blocks or the C++ language affect book content. You can also access other cool materials:
Cheat Sheet:
You remember using crib notes in school to make a better mark on a test, don’t you? You do? Well, a cheat sheet is sort of like that. It provides you with some special notes on things you can do with C++ that not every other developer knows. You can find the cheat sheet for this book at
www.dummies.com
and typing
C++ All-in-One For Dummies, 4th Edition
in the search field. It contains really neat information like the top ten mistakes developers make when working with C++, a list of header files that you use in most applications, and some of the C++ syntax that gives most developers problems.
Updates:
Sometimes changes happen. For example, I might not have seen an upcoming change when I looked into my crystal ball during the writing of this book. In the past, such a situation simply meant that the book would become outdated and less useful, but you can now find updates to the book at
www.dummies.com
. In addition to these updates, check out the blog posts with answers to reader questions and demonstrations of useful book-related techniques at
http://blog.johnmuellerbooks.com/
.
Companion files: Hey! Who really wants to type all the code in the book? Most readers would prefer to spend their time actually working through coding examples rather than typing. Fortunately for you, the source code is available for download, so all you need to do is read the book to learn C++ coding techniques. Each of the book examples even tells you precisely which example project to use. You can find these files by visiting www.dummies.com/go/caiofd4e.
Just in case you’re worried about Code::Blocks, you can find complete download and installation instructions for it in Book 1, Chapter 1. Don’t worry about which platform you use. This chapter includes instructions for Mac OS X, Linux, and Windows.
If you’re just starting your C++ adventure, I highly recommend starting at either Book 1, Chapter 1 (for desktop developers) or Book 1, Chapter 2 (for mobile developers). You really do need to create a solid foundation before you can tackle the code in this book. If you’re in a hurry and already have a C++ installation, you can always try starting with Book 1, Chapter 3.
Readers with a little more experience, who already know some C++ basics, can skip some of these introductory chapters, but you definitely don’t want to skip Book 1, Chapter 8 because it contains a lot of pointer-related changes in current versions of C++. If you skip this chapter, you may find later that you have a hard time following the example code in the book because the newer examples use these pointer features.
An advanced reader with some idea of the current changes in C++ 20 could possibly skip Book 1, but scanning Book 2 is a good idea because there are some OOP changes you definitely want to know about. However, even for advanced readers, skipping Book 3 is a bad idea because modern development really is moving toward functional programming techniques.
Book 1
Chapter 1: Configuring Your Desktop System
Obtaining a Copy of C++ 20
Obtaining Code::Blocks
Installing Code::Blocks
Touring the Essential Code::Blocks Features
Using Other IDEs
Chapter 2: Configuring Your Mobile System
Obtaining CppDroid
Considering Other Alternatives
Touring the Essential CppDroid Features
Obtaining CppDroid Help
Chapter 3: Creating Your First C++ Application
Code::Blocks Creating a Project
Typing the Code
Starting with Main
Showing Information
Let Your Application Run Away
Chapter 4: Storing Data in C++
Putting Your Data Places: Variables
Manipulating Integer Variables
Characters
Strings
Making Decisions Using Conditional Operators
Telling the Truth with Boolean Variables
Reading from the Console
Chapter 5: Directing the Application Flow
Doing This or Doing That
Evaluating Conditions in C++
Including Evaluations in C++ Conditional Statements
Repeating Actions with Statements That Loop
Looping for
Looping while
Doing while
Breaking and continuing
Nesting loops
Chapter 6: Dividing Your Work with Functions
Dividing Your Work
Calling a Function
Writing Your Own Functions
Improving On the Basic Function
Calling All String Functions
Understanding main()
Chapter 7: Splitting Up Source Code Files
Creating Multiple Source Files
Sharing with Header Files
Sharing Variables among Source Files
Using the Mysterious Header Wrappers
Chapter 8: Referring to Your Data Through Pointers
Understanding the Changes in Pointers for C++ 20
Heaping and Stacking the Variables
Creating New Raw Pointers
Freeing Raw Pointers
Working with Smart Pointers
Passing Pointer Variables to Functions
Returning Pointer Variables from Functions
Chapter 1
IN THIS CHAPTER
Getting your own copy of C++ 20
Getting a copy of Code::Blocks
Creating a Code::Blocks work environment on your system
Seeing how Code::Blocks helps you perform tasks
Working with other IDEs
This chapter is for those of you who have a desktop system and want to use it to create your application code. Chapter 2 discusses how to perform the same task using a mobile device (and provides you with some trade-offs between the two environments). Whether you use the desktop or the mobile solution, you need a copy of a compiler that supports C++ 20 features or some book examples won’t work at all. This book relies on the GNU Compiler Collection (GCC) version 8.3 compiler because it provides great C++ 20 support (see https://en.cppreference.com/w/cpp/compiler_support). The best way to obtain the version 8.3 compiler for your desktop system is to follow the steps in this chapter.
Before you can do anything interesting at all with C++, you need a copy of it installed on your system. Of course, this means going online, finding the location of the software that’s appropriate for your platform, and then downloading it as necessary. If you use an Integrated Development Environment (IDE) such as Code::Blocks (the IDE used throughout this book), you get a copy of C++ with your installation, so you don’t need to worry about reading the first section of this chapter. This book relies on your having a compiler capable of compiling C++ 20 code, which is the latest version of the language available at the time of this writing.
Even though this book focuses on working with C++ on the Mac, Windows, and Linux platforms, you can actually use the techniques it provides on a great many other desktop systems. With this in mind, you’ll find an overview of using C++ with other IDEs. As your platform becomes more esoteric, you’ll find that fewer of the book examples work because your platform may require special programming techniques. The best option for working with this book is using a copy of Code::Blocks 17.12 with C++ 20 support installed on the Linux, Mac, or Windows platform.
There is no product available named C++ 20. The C++ 20 standard simply says what the language contains and how someone should implement it. In other words, you can’t just go online and get a copy of C++ 20; what you need to do instead is get a compiler vendor’s implementation of the C++ 20 standard. For example, you can download the GNU Compiler Collection (GCC) version of C++ 20 from https://gcc.gnu.org/releases.html.
Every vendor will have a slightly different interpretation of this standard and could provide additions to the standard. In short, every compiler provides a unique version of C++. However, you also have the choice of not using the special features that the vendor provides, which means your source code is less susceptible to problems that occur when you use multiple compilers. The examples in this book are strictly written to the C++ 20 standard, so you shouldn’t have a problem using them anywhere you want.
It’s important that you also understand that a compiler is not the same as an Integrated Development Environment (IDE). The compiler is separate from the IDE in many cases and maintained by two separate parties. For example, the Code::Blocks IDE supports multiple compilers, and the GCC compiler works within multiple IDEs. The compiler is the important piece of software that turns your source code into an executable file that the operating system can run to produce the output you want.
The compiler you choose has to support the platforms you want to work with. For example, GCC supports Mac, Windows, and Linux development as well as some Acorn or (later) Advanced RISC Machine (ARM) processors (ARM doesn’t officially stand for anything today). In fact, it may support other platforms by the time you read this chapter. Because it works in so many places, this book focuses on GCC, even though the examples will work with other compilers with some modification to overcome compiler differences.
The Code::Blocks IDE provides an environment in which you can write source code, compile it, test it, and debug it as needed. The IDE doesn’t actually compile the source code, but it does provide support for a compiler that does so. (It just so happens that it does its job in such a way that makes it appear that the compiler is part of the IDE.) You can choose from a number of compilers in Code::Blocks, but this book focuses on using GCC to ensure that the examples will run on as many platforms as possible. GCC comes with your copy of Code::Blocks when working with Windows, so you don’t have to do anything special to work with it except select it during the installation process. (When working on a Mac or Linux system, you must install GCC separately — the compiler doesn’t come with Code::Blocks.)
This book is written using Code::Blocks version 17.12. That doesn’t mean you can’t use it with earlier or later versions of Code::Blocks. However, when working with other versions of Code::Blocks, you may find that you need to modify the code slightly. The modification is required in order to support the compiler that comes with that version of Code::Blocks. The IDE itself won’t affect your ability to work with C++ 20.
Code::Blocks comes in both binary form and source code form. You can download either form of version 17.12 from http://www.codeblocks.org/downloads/5. The link leads you to SourceForge, where you select the platform you want to use: Mac, Linux, or Windows. Click the folder link and you see a list of downloadable archive files for that platform. (Linux users will also have to choose their particular version of Linux.) Choosing the correct archive is important because different archives have different features.
When working with a Windows installation, make sure you use the codeblocks-17.12mingw-setup.exe installer to obtain a copy of GCC with Code::Blocks. Make absolutely certain that you don’t install it to the Program Files folder on your system, because the application won’t work there. Code::Blocks writes data to its host directory, and Windows won’t allow applications to perform this task in the Program Files folder. Create a folder to which you have write privileges and install Code::Blocks there instead.
Now that you have an appropriate archive to use, it’s time to install Code::Blocks on your machine. The “Installing Code::Blocks” section of this chapter tells you more about getting Code::Blocks installed on your particular system.
Before you can use Code::Blocks as your IDE, you need to install it. The following sections describe how to install Code::Blocks on each of the main platforms supported by this book. The instructions in these sections assume that you’ve downloaded the binary version of Code::Blocks and that you aren’t using a custom compiled version of the product.
If you have an older version of Code::Blocks installed on your system, be sure to uninstall it before installing the new version. Also make sure that you tell the uninstaller to delete any old custom files in the folder so that you start with a fresh folder. Old files can cause errors to appear when you start Code::Blocks or perform common tasks.
Code::Blocks comes with a Windows installer that will make the task of installing the IDE easier. The following steps help you work with the codeblocks-17.12mingw-setup.exe installer:
Double-click the file you downloaded from the Code::Blocks site.
You see the CodeBlocks Setup Wizard start. If you see a User Account Control dialog box, give the application permission to proceed by clicking Yes.
Click Next.
The licensing agreement appears. Read the licensing agreement so that you know the terms of usage for Code::Blocks.
Click I Agree.
The wizard displays a series of configuration options, as shown in Figure 1-1. This book assumes that you’ve performed the default, full installation.
Click Next.
The installation program asks where to install Code::Blocks on your system. Unlike many other applications, Code::Blocks will actually write data to this folder from time to time. The best idea is to use a folder to which you have write access. To ensure maximum compatibility, the book uses the C:\CodeBlocks folder for installation purposes. To keep from seeing any error messages, make sure that the path doesn’t have any spaces in it (see the blog post at http://blog.johnmuellerbooks.com/2016/04/20/spaces-in-paths/ for details).
FIGURE 1-1: The wizard asks you to select the configuration options to use.
Type C:\CodeBlocks in the Destination Folder field. Click Install.
The installation program automatically creates the C:\CodeBlocks folder for you when it doesn’t already exist. If the folder already exists because you previously installed an older version of Code::Blocks, you see a dialog box appear. Click Yes to allow installation to continue. You see all the files installed into the C:\CodeBlocks folder on your system.
The setup wizard may display a dialog box asking whether you want to start Code::Blocks. Click No if you see this dialog box.
Click Next.
You see a completion dialog box.
Click Finish.
The setup wizard ends.
If you find that the wizard has somehow managed not to select a compiler and/or debugger for you, you can perform this task manually. The “Selecting a compiler” section will help in this regard. In addition, the blog posts at http://blog.johnmuellerbooks.com/2011/04/06/checking-your-compiler-in-codeblocks/ and http://blog.johnmuellerbooks.com/2013/04/12/resetting-your-codeblocks-configuration/ tell how to perform the additional setup. However, in most cases, the wizard will perform the required setup for you.
Installing Code::Blocks on a Mac requires a little extra work than it does in Windows. Code::Blocks requires Mac OS X 10.6 or later to install. You can get the version 17.12 file, codeblocks-17.12_OSX64.dmg, from https://sourceforge.net/projects/codeblocks/files/Binaries/17.12/Mac/. If you experience a Mac Gatekeeper error during installation, please check out the blog post at http://blog.johnmuellerbooks.com/2016/03/21/mac-gatekeeper-error/.
The following steps tell you how to get a functional Code::Blocks installation on your Mac system.
Download and install Xcode from the App Store to obtain a copy of GCC, if necessary.
You can verify that you have the GNU GCC compiler installed by opening a terminal, typing gcc -v, and pressing Enter. If GCC is installed, you should see some version information along with some compiler instructions.
Extract the Code::Blocks files into a folder.
You see a number of files, including the Code::Blocks application, a readme file containing the latest update information, and a PDF file containing documentation.
Open the Applications folder.
You see the applications installed on your system.
Drag the CodeBlocks.app file from the folder you used for extraction purposes to the Applications folder.
The operating system adds Code::Blocks to the list of usable applications.
Navigate tohttps://developer.apple.com/downloads/.
This site requires that you sign up for a free developer ID. Simply follow the prompts onscreen to obtain your Apple ID. The sign-up process is free.
Click the Command Line Tools for Xcode link.
The operating system downloads the file and displays a package folder for you.
Double-click the Command Line Tools package.
The operating system installs the package for you, which enables access to GCC from Code::Blocks.
There isn’t a single set of steps for installing Code::Blocks on Linux, because each flavor of Linux has its own requirements. Code::Blocks directly supports:
Blag
Debian
Fedora
Gentoo
Platypux
Red Hat Package Manager (RPM)-based distributions (such as SUSE, Red Hat, Yellow Dog, Fedora Core, and CentOS)
Ubuntu
Each distribution type has its own set of instructions that you can find at http://wiki.codeblocks.org/index.php?title=Installing_Code::Blocks. Make sure you download and install the compiler, debugger, and IDE as needed by carefully following the instructions (typed at the terminal). The file that you download from http://www.codeblocks.org/downloads/26 contains the packages for a Code::Blocks installation, so you don’t need to download each package separately as part of the installation process.
Some Linux installations have special requirements or experience limitations when working with Code::Blocks. The only apparent limitation that affects this book is the lack of Boost support for Red Hat and CentOS. Because of this limitation, you can’t use the examples found in Book 7, Chapters 4 and 5. However, if you experience other limitations, please let me know about them at [email protected] and I’ll address them as part of a blog post for this book.
All versions of Linux support the standard installation discussed in the “Using the standard Linux installation” section of this chapter. However, a few versions of Debian-based Linux distributions, such as Ubuntu 12.x and above, provide a graphical installation technique as well. You’ll need the administrator group (sudo) password to use this procedure, so having it handy will save you time. The following steps outline the graphical installation technique for Ubuntu, but the technique is similar for other Linux installations.
Open the Ubuntu Software Center folder (the folder may be named Synaptics on other platforms).
You see a listing of the most popular software available for download and installation, as shown in Figure 1-2. Your list will probably vary from the one shown in the screenshot.
Select Developer Tools (or Development) from the All Software drop-down list box.
You see a listing of developer tools, including Code::Blocks, as shown in Figure 1-3.
FIGURE 1-2: The Ubuntu Software Center contains a list of the most popular software when you open it.
FIGURE 1-3: The Developer Tools category contains an entry for Code::Blocks.
Double click the Code::Blocks entry.
The Ubuntu Software Center provides details about the Code::Blocks entry and offers to install it for you, as shown in Figure 1-4.
FIGURE 1-4: It’s possible to obtain additional information about Code::Blocks if necessary.
Click Install.
Ubuntu begins the process of installing Code::Blocks. A progress bar shows the download and installation status. When the installation is complete, the Install button changes to a Remove button.
Close the Ubuntu Software Center folder.
You see a Code::Blocks icon added to the Desktop. The IDE is ready for use.
No matter how you install Code::Blocks for your platform, you eventually end up with an IDE with standardized characteristics. This is one of the best reasons to use an IDE such as Code::Blocks — you can use the same IDE no matter which platform you use.
Your screenshots may look different from the ones shown in this book. Even though this book uses screenshots from the Windows version of Code::Blocks, the same features are provided for Code::Blocks installations on other platforms, though the IDE may not look precisely the same on those other platforms. The following sections describe the essential features you need to know about when working with Code::Blocks.