C++20 for Lazy Programmers: Quick, Easy, and Fun C++ for Beginners 2nd Edition Will Briggs instant download
C++20 for Lazy Programmers: Quick, Easy, and Fun C++ for Beginners 2nd Edition Will Briggs instant download
https://textbookfull.com/product/c20-for-lazy-programmers-quick-
easy-and-fun-c-for-beginners-2nd-edition-will-briggs/
https://textbookfull.com/product/primary-mathematics-
textbook-2b-jennifer-hoerst/
https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-
loucas/
https://textbookfull.com/product/handbook-of-macroeconomics-
volume-2a-2b-set-1st-edition-john-b-taylor/
https://textbookfull.com/product/c-20-for-programmers-3rd-
edition-harvey-deitel/
C# Programming for Absolute Beginners Radek Vystav■l
https://textbookfull.com/product/c-programming-for-absolute-
beginners-radek-vystavel/
https://textbookfull.com/product/modern-c-for-absolute-beginners-
a-friendly-introduction-to-the-c-programming-language-2nd-
edition-slobodan-dmitrovic/
https://textbookfull.com/product/c-7-0-pocket-reference-instant-
help-for-c-7-0-programmers-1st-edition-joseph-albahari/
https://textbookfull.com/product/modern-c-for-absolute-
beginners-1st-edition-slobodan-dmitrovic/
https://textbookfull.com/product/modern-c-for-absolute-beginners-
second-edition-solbodan-dmitrovic/
Will Briggs
The publisher, the authors and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
Why SDL?
It’s surely more enjoyable to make programs with graphics and WIMP2-
style interaction than to merely type things in and print them out.
There are a variety of graphical libraries out there. SDL , or Simple
DirectMedia Layer, is popular, relatively easy to learn, portable between
platforms, and fast enough for real-world work, as evidenced by its use
in actual released games.
Figure 1 A game of Freeciv, which uses the SDL library
Why SSDL?
…but although SDL is relatively easy, it’s not simple enough to start on
day 1 of programming with C++. SSDL – simple SDL – saves you from
needing to know things we don’t get to until Chapter 143 before doing
basic things like displaying images (Chapter 2) or even printing a
greeting (Chapter 1). It also hides the initialization and cleanup code
that’s pretty much the same every time you write a program and makes
error handling less cumbersome.
You may want to keep using SSDL as is after you’re done with this
book, but if you decide to go on with SDL, you’ll find you know a lot of it
already, with almost nothing to unlearn: most SSDL function names are
names from SDL with another “S” stuck on the front. We’ll go into
greater depth on moving forward with SDL in Chapter 29.
(Free) software you will need
At the time of writing, Microsoft Visual Studio (Community Edition) for
Windows is absolutely free, and g++ always is. So are the SSDL and
SDL2 libraries; Microsoft Core fonts for the Web , which you’ll need on
Unix systems; and the GIMP deluxe graphics editing package. See
Chapter 1 and Appendix A for help installing these essentials.
Programming with sound may not be practical over remote
connections because of the difficulty of streaming sound. If using Unix
emulation, you might check the emulator’s sound capabilities – say, by
playing a video.
Online help
Here are some sites to go to for more information, with URLs correct at
the time of writing:
SDL : www.libsdl.org . Click “Wiki.” You’ll find a reference for
SDL functions.
SDL’s helper libraries SDL_Image, SDL_Mixer, and SDL_TTF:
www.libsdl.org/projects/SDL_image/,
www.libsdl.org/projects/SDL_mixer/ , and
www.libsdl.org/projects/SDL_ttf/ . In each case, click
Documentation. You’ll find references for their functions. If the websites
have changed, doing a web search for the name of the library (e.g.,
SDL_Image) should get you there.
Legal stuff
Visual Basic, Visual Studio, Windows, Windows Vista, Excel, and
Microsoft are trademarks of the Microsoft Corporation. All other
trademarks referenced herein are property of their respective owners.
This book and its author are neither affiliated with nor authorized,
sponsored, or approved by the Microsoft Corporation.
Screenshots of Microsoft products are used with permission from
Microsoft.
Acknowledgments
Special thanks to
Dr. Kim McCabe, for advice on publishing.
Dr. Zakaria Kurdi, for the same.
Apress, especially Steve Anglin.
Microsoft.
The makers of GIMP (the GNU Image Manipulation Program).
Pixabay.com and contributors, especially 3D Animation Production
Company/QuinceCreative (Chapter 1, bullseye), David Mark/12019
(Chapter 2, beach), Free-Photos (Chapter 2, pug), Andi
Caswell/andicaz (Chapter 6, scones), joakant (Chapter 11, tropical
fish), Gerhard Janson/Janson_G (Chapter 12, UFO), 13smok (Chapter
12, alien sign), Prawny (Chapter 12, splat), Elliekha (Chapter 12,
haunted house), pencil parker (Chapter 12, candy), and Robert
Davis/rescueram3 (Chapter 12, pumpkin photos).
Wikimedia Commons.
OpenClipArt.org and contributors, especially Firkin (Chapter 2,
flamingo).
Flickr, especially Speedy McZoom (Chapter 12, jack-o’-lantern art).
FreeSound.org and contributors, especially Razor5 (Chapters 1 and 2,
techno music), robbo799 (Chapter 2, church bells), alqutis (Chapter
12, hover car), Berviceps (Chapter 12, splat), mistersherlock
(Chapter 12, Hallowe’en graveyard), matypresidente (Chapter 12,
water drop), Osiruswaltz (Chapter 12, bump), mrose6 (Chapter 12,
echoed scream), and robcro6010 (Chapter 12, circus theme).
Chad Savage of Sinister Fonts for Werewolf Moon (Chapter 12).
Lazy Foo’ Productions.
StackOverflow.com.
Einar Egilsson of cardgames.io for images of card games and Nicu
Buculei ( http://nicubunu.ro/cards ) for card images.
The alumni and colleagues who gave me reviews. You’re the best!
Table of Contents
Chapter 1:Getting Started
Initial setup
…in Unix
…in MinGW
…in Microsoft Visual Studio
A simple program
Spacing
Creating an SSDL project
…with g++ (Unix or MinGW)
…in Microsoft Visual Studio
How not to be miserable (whatever your platform)
Shapes and the functions that draw them
consts and colors
Text
sout, escape sequences, and fonts
SSDL_RenderText, SSDL_RenderTextCentered
Chapter 2:Images and Sound
Images and window characteristics
Multiple images together
Adding transparency with GIMP
Sound
Chapter 3:Numbers
Variables
Constants
When to use constants, not literal values
Math operators
Integer division
Assignment (=) operators
A diving board example
The no-worries list for math operators
Built-in functions and casting
Chapter 4: Mouse, and if
Mouse functions
if
Coercion and if conditions (if’s dirty little secret)
Combining conditions with &&, ||, and !
Boolean values and variables
A hidden object game
Chapter 5: Loops, Input, and char
Keyboard input
while and do-while
Loops with SSDL
break and continue
for loops
Increment operators
An example:Averaging numbers
chars and cctype
switch
Chapter 6:Algorithms and the Development Process
Adventures in robotic cooking
Writing a program, from start to finish
Requirements:What do we want to do?
Algorithm:How do we do it?
Trace the algorithm:Will it work?
Coding:Putting it all into C++ (plus:commenting the lazy
way)
Chapter 7:Functions
Functions that return values
Functions that return nothing
Global variables
How to write a function in four easy steps (and call it in one)
Why have functions, anyway?
Recap
Chapter 8:Functions, Continued
Random numbers
Making a random number generator
Using the built-in random number generator
Boolean functions
& parameters
Identifier scope
A final note on algorithms
Chapter 9:Using the Debugger
Breakpoints and watched variables
ddd
gdb
Visual Studio
Fixing the stripes
Going into functions
ddd
gdb
Visual Studio
Fixing the stars
Wrap-up
Bottom-up testing
More on antibugging
Chapter 10: Arrays and enum
Arrays
Arrays’ dirty little secret:using memory addresses
Arrays as function parameters
Array parameters that change, or don’t
Array parameters and reusability
Enumeration types
Multidimensionalarrays
Displaying the board
Arrays of more than two dimensions
Chapter 11:Animation with structs and Sprites
structs
Making a movie with struct and while
Sprites
Chapter 12:Making an Arcade Game:Input, Collisions, and Putting
It All Together
Determining input states
Mouse
Keyboard
Events
Cooldowns and lifetimes
Collisions
The big game
Chapter 13:Standard I/O and File Operations
Standard I/O programs
Compiling standard I/O programs
Building a project from scratch (optional)
File I/O (optional)
cin and cout as files
Using filenames
Chapter 14:Character Arrays and Dynamic Memory
Character arrays
Dynamic allocation of arrays
Using the * notation
Chapter 15:Classes
Constructors
const objects, const member functions…
…and const parameters
Multiple constructors
Copy constructors
Default constructors
Conversion constructors
Summary
Default parameters for code reuse
Date program (so far)
Chapter 16:Classes, Continued
inline functions for efficiency
Access functions
Separate compilation and include files
What happens in separate compilation
Writing your .h file
Backing up a multi-file project
Multiple-file projects in Microsoft Visual Studio
Multiple-file projects in g++
Command line:more typing, less thinking
Makefiles:more thinking, less typing (optional)
Final Date program
Chapter 17:Operators
The basic string class
Destructors
Binary and unary operators:==, !=, and !
All other comparison operators at once
Assignment operators and *this
Arithmetic operators
[ ] and ( )
++ and --
>> and <<: operators that aren’t class members
static members
Explicit call to constructor
The final String program
#include <string>
Chapter 18:Exceptions, Move Constructors and =, Recursion, and O
notation
Exceptions
Move constructors and move =(optional)
Recursion (optional; referenced in the next section)
Efficiency and O notation (optional)
Chapter 19:Inheritance
The basics of inheritance
Constructors and destructors for inheritance and member
variables
Inheritance as a concept
Classes for card games
An inheritance hierarchy
private inheritance
Hiding an inherited member function
A game of Montana
Chapter 20:Templates
Function templates
Concepts for function templates (optional)
The Vector class
Efficiency and O notation (optional)
Making Vector a template
Concepts for class templates (optional)
pair
Non-type template arguments
#include <vector>
Chapter 21:Virtual Functions and Multiple Inheritance
Virtual functions, plus:move functions with movable parents
and class members
Behind the scenes
Pure virtual functions and abstract base classes
Why virtual functions often mean using pointers
Virtual destructors
Move functions with movable parents and class members
(optional)
Multiple inheritance (optional)
Chapter 22:Linked Lists
What lists are and why have them
Efficiency and O notation (optional)
Starting the linked list template
List<T>::List ( )
void List<T>::push_front (const T& newElement);
void List<T>::pop_front ( )
List<T>::~List ( )
->: a bit of syntactic sugar
More friendly syntax:pointers as conditions
The linked list template
#include <list>
Chapter 23:The Standard Template Library
Iterators
…with vector too
const and reverse iterators
Getting really lazy:range-based for and auto
Spans
initializer_lists (optional)
<algorithm> (optional)
Chapter 24:Building Bigger Projects
Namespaces
Conditional compilation
Libraries
g++
Microsoft Visual Studio
Chapter 25:Esoterica (Recommended)
sstream: using strings like cin/cout
Formatted output with format strings
Command-line arguments
Debugging with command-line arguments in Unix
Debugging with command-line arguments in Visual Studio
Bit manipulation:&, |, ~, and <</>>
Chapter 26:Esoterica (Recommended), Continued
Defaulted constructors and =
constexpr and static_assert: moving work to
compile time
Structured bindings and tuples:returning multiple values at
once
Smart pointers
unique_ptr
shared_ptr
static_cast et al.
User-defined literals:automatic conversion between systems of
measurement
Lambda functions for one-time use
Lambda captures
An example with lambda functions
Chapter 27:Esoterica (Not So Recommended)
protected sections, protected inheritance
friends and why you shouldn’t have any
User-defined conversions (cast operators)
Modules
Coroutines
Chapter 28:C
Compiling C
I/O
printf
scanf and the address-of (&) operator
fprintf and fscanf, fopen and fclose
sprintf and sscanf; fgets, fputs, and puts
Summary of commands
Parameter passing with *
Dynamic memory
Chapter 29:Moving on with SDL
Writing code
Compiling
Further resources
Appendix A:Help with Setup
…for Unix users
Debian/Ubuntu
RedHat/Fedora
SSDL
…for MinGW users
…for Microsoft Visual Studio users
…for other platforms
Sound
Making your own projects
...in g++
…in Microsoft Visual Studio
Appendix B:Operators
Associativity
Precedence
Overloading
Appendix C:ASCII Codes
Appendix D:Fundamental Types
Appendix E:Escape Sequences
Appendix F:Basic C Standard Library
cmath
cctype
cstdlib
Appendix G:Common Debugger Commands
Microsoft Visual Studio
gdb/ddd
Appendix H:SSDL Reference
Updating the screen
Added types
Clearing the screen
Colors
Drawing
Images
Mouse, keyboard, and events
Music
Quit messages
Sounds
Sprites
Text
Time and synchronization
Window
References
Index
About the Author
Will Briggs
PhD, is a professor of computer science at the University of Lynchburg
in Virginia. He has 20+ years of experience teaching C++, 12 of them
using earlier drafts of this book and about as many years teaching other
languages including C, LISP, Pascal, PHP, PROLOG, and Python. His
primary focus is teaching of late while also pursuing research in
artificial intelligence.
About the Technical Reviewer
Charles A. Bell
conducts research in emerging
technologies. He is a principal software
developer of the Oracle MySQL
Development team. He lives in a small
town in rural Virginia with his loving
wife. He received his Doctor of
Philosophy in Engineering from Virginia
Commonwealth University in 2005.
Dr. Bell is an expert in the database
field and has extensive knowledge and
experience in software development and
systems engineering. His research
interests include microcontrollers, three-dimensional printing,
database systems, software engineering, and sensor networks. He
spends his limited free time as a practicing maker focusing on
microcontroller projects and refinement of three-dimensional printers.
Footnotes
1 “Eye candy”: things that look good on the screen. See The New Hacker’s Dictionary,
available at the time of writing at www.catb.org/jargon/ .
2 WIMP: window, icon, mouse, pointer. What we’re all used to.
3 Pointers.
© Will Briggs 2021
W. Briggs, C++20 for Lazy Programmers
https://doi.org/10.1007/978-1-4842-6306-8_1
1. Getting Started
Will Briggs1
(1) Lynchburg, VA, USA
Most programs in the first half of this book use the SDL and SSDL graphics-and-
games libraries,1 on the theory that watching colorful shapes move across the screen
and shoot each other is more interesting than printing text. Don’t worry. When you’re
done, you’ll be able to write programs both with and without this library – and if I
have anything to say about it, you’ll have had fun doing it.
If you’ve already chosen your platform, great. If not, here’s my recommendation:
If you just want to learn C++ on an easy and easily managed platform, Microsoft
Visual Studio is great.
If you are a Unix system administrator or have good access to one, and want to
use that popular and powerful platform, go for it.
To learn g++ and make – powerful tools from the Unix world – in Windows,
with a relatively easy setup, use MinGW.
The programming won’t differ much between platforms. But system setup can be
an issue.
Initial setup
First, you’ll need the source code for the textbook. You can access the code via the
Download Source Code button located at www.apress.com/9781484263051.
Then unzip it. In Unix, the unzip command should work; in Windows, you can
usually double-click it or right-click and choose Extract or Extract All.
…in Unix
Getting around in Unix isn’t in the scope of this book, but no worries. The basics of
copying files, moving files, and so on are easy to pick up.2
Unix system administration is way beyond the scope of this book.3 But installing
SSDL is easy. In that folder you just unzipped
Go into external/SSDL/unix, and type make. This builds SSDL in a place
where programs in the source code will know where to find it.
Go into ch1/test-setup.
cp Makefile.unix Makefile
make
./runx
You should see (and hear) the program illustrated in Figure 1-1. (If not,
something must be missing – please see Appendix A.) You might take a moment to try
another program from ch1, like 1-hello. Run it the same way you did test-
setup.
…in MinGW
You can find MinGW at sourceforge.net and other places. Try a web search on
“MinGW download.”
Once that’s installed, have it add the basics for C++; start the MinGW Installation
Manager (mingw-get.exe) and have it install, at least, mingw32-gcc-g++-bin,
mingw32-gdb-bin, and msys-make-bin.
You won’t need to install SDL or SSDL; they’re in the source code you unzipped.
So let’s try ‘em out. Open the Windows command prompt (click the Start Menu
and type cmd) and go to the source code’s ch1/test-setup folder. Here’s an easy
way: in the window for that folder, click the folder icon left of the address bar, the
part that shows something like ... > ch1 > test-setup. It’ll be replaced by a
highlighted path like the one in Figure 1-2. Press Ctrl-C to copy it.
Figure 1-2 Getting a path to use with the command prompt, in Windows
In the command window, enter the first two characters of that path you copied
(in my case, C:); then type cd, paste in the path (Ctrl-V), and press Enter again (see
Figure 1-3).
Then
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com