Table Of ContentTopic Subtopic
Science & Mathematics Technology
Introduction to C++
Programming Concepts
and Applications
Professor John Keyser
Texas A&M University
Published by
THE GR EAT COURSES
Corporate Headquarters
| | |
4840 Westfields Boulevard Suite 500 Chantilly, Virginia 20151‑2299
| |
[phone] 1.800.832.2412 [fax] 703.378.3819 [web] www.thegreatcourses.com
Copyright © The Teaching Company, 2019
Printed in the United States of America
This book is in copyright. All rights reserved. Without limiting the rights under copyright reserved
above, no part of this publication may be reproduced, stored in or introduced into a retrieval system,
or transmitted, in any form, or by any means (electronic, mechanical, photocopying, recording, or
otherwise), without the prior written permission of The Teaching Company.
Joh n Keyse r, Ph D
Professor of Computer Science and Engineering
Texas A&M University
John Keyser is a Professor of Computer of biological data, reconstructing the
Science and Engineering at Texas A&M geometric structures in that data, and helping
University. He earned his PhD in Computer visualize the results in effective ways. In
Science from the University of North Carolina. addition, he has published papers on a variety
As an undergraduate, he earned 3 bachelor's of other graphics topics, including rendering
degrees—in Computer Science, Engineering and modeling.
Physics, and Applied Math—from Abilene
Christian University. Professor Keyser's teaching has spanned
a range of courses, from introductory
Professor Keyser's interests in physics, undergraduate courses in programming;
math, and computing led him to a career in through upper-level undergraduate courses Excellence, and he has received other awards,
computer graphics, which has allowed him in graphics, programming, and software including the Tenneco Meritorious Teaching
to combine all 3 disciplines. He has published development; to graduate courses in graphics Award and the Theta Tau Most Informative
several articles in geometric modeling, modeling and simulation. Among these, he Lecturer Award.
particularly looking at ways of quantifying created a course called Programming Studio
and eliminating uncertainty in geometric that has become required for all Computer Since writing his first computer program more
calculations. Professor Keyser has been a long- Science and Computer Engineering majors than 35 years ago, Professor Keyser has loved
standing member of the solid and physical at Texas A&M, and he helped develop the computer programming. He has particularly
modeling community, including previously introductory programming course taught to all enjoyed programming competitions, both as
serving on the Solid Modeling Association Texas A&M Engineering students. a student competitor and as a team coach. Of
executive committee. He has also published the many computer science classes he took,
several articles and coauthored a textbook Professor Keyser has won several teaching the most important class turned out to be the
in physically based simulation for graphics awards at Texas A&M, including the one in which he met his wife. In his free time, he
(Foundations of Physically Based Modeling Distinguished Achievement Award in Teaching, enjoys traveling with her and their 2 daughters.
and Animation). As a member of the Brain which he received once at the university level
Networks Laboratory collaboration at Texas and twice from the College of Engineering. Professor Keyser's other Great Course is How
A&M, he has worked on developing a new As an assistant professor, he was named a to Program: Computer Science Concepts and
technique for rapidly scanning vast amounts Montague Scholar by the Center for Teaching Python Exercises.
i
P rofessor Biography
Table of Contents
Professor Biography Booleans and Conditionals in C++
i 03 31
...................................... ...................
Boolean Variables
31
Course Scope
1
............................................
Comparison Operators
34
Conditional Statements
35
Compiling Your First C++ Program
01 2
....................
Quiz
42
Introduction to Computer Programming
2
Quiz Answers
43
What Happens When You Program
3
Your First Program
4 Program Design and Writing Test Cases in C++
04 44
.......
Quiz
8
The Structure of a C++ Program
44
Quiz Answers
9
Designing and Testing Your Program
46
Quiz
52
C++ QUICK START: With Browser or Download
01b 10
.......
Quiz Answers
53
Introduction
10
Quick Start with a Browser
11 C++ Loops and Iteration
05 54
.............................
Quick Start with an IDE
14
Loops
While 54
Loops
For 57
Variables, Computations, and Input in C++
02 17
...........
Scope of Variables
61
Variables and Computations
17
Quiz
63
Variable Declarations
19
Quiz Answers
64
Variable Assignments
21
Computing Calories
22 Importing C++ Functions and Libraries
06 65
...............
Incrementing Variables
23
Code Libraries
65
How C++ Supports Mathematical
How Code and Libraries Are Compiled
Functions
25
in C++
66
Input
26
The C++ Standard Library
67
Quiz
29
Random Numbers
69
Quiz Answers
30
Quiz
74
Quiz Answers
75
NAVIGATION TIP
To go back to the page you came from, press Alt + ← on a PC or ⌘ + ← on a Mac. On a tablet, use the bookmarks panel.
ii
Table of Contents
Arrays for Quick and Easy Data Storage Creating Your Own Functions in C++
07 76 12 131
............. ................
Storing Variables in Memory Functions as Black Boxes
76 131
Indexing into an Array Creating Your Own Functions
78 132
Initializing an Array The Function Body
81 134
Array Bounds Conceptual Separation
83 135
Quiz Scope
84 138
Quiz Answers Quiz
85 142
Quiz Answers
143
Vectors for Safe and Flexible Data Storage
08 86
...........
Expanding What Your Functions Can Do in C++
Using Vectors 13 144
86 .....
Vector Size Initialization Overloading Functions
89 144
Vector Resizing Setting Default Parameters
91 148
Performing Out-of-Bounds Checks Using References
92 149
Assigning Vectors Quiz
94 152
Quiz Quiz Answers
95 153
Quiz Answers
96
Systematic Debugging, Writing Exceptions
14 154
..........
C++ Strings for Manipulating Text
09 98 A Systematic Approach to Debugging
.................... 154
String Variables and Literals Types and Sources of Errors
98 159
String Operations Using Exceptions
102 160
Char-Type Variables Quiz
103 163
Quiz Quiz Answers
107 164
Quiz Answers
108
Functions in Top-Down and Bottom-Up Design
15 165
.....
Files and Stream Operators in C++
10 109 Top-Down Design
.................. 165
File Streaming Bottom-Up Design
109 169
String Streaming Building a Library
113 171
Quiz Quiz
116 173
Quiz Answers Quiz Answers
117 174
Top-Down Design and Using a C++ Debugger Objects and Classes: Encapsulation in C++
11 119 16 175
....... ..........
Top-Down Design Object-Oriented Programming
119 175
Incremental Development Creating Classes
122 177
Debugger Tool Sorting Data in Classes
124 177
Quiz Public versus Private
128 181
Quiz Answers Quiz
129 185
Quiz Answers
186
iii
Table of Contents
Object-Oriented Constructors and Operators Using Classes to Build a Game Engine in C++
17 187 21 241
........ ........
Constructors Designing Classes
187 241
Operator Overloading Coding Your Design
190 246
Overloading Binary Operators Quiz
191 250
Overloading Unary Operators Quiz Answer
195 251
Friend Functions
197
C++ Templates, Containers, and the STL
22 252
............
Overloading Stream Operators
198
Templates and Containers
252
Quiz
200
Stacks
254
Quiz Answers
201
Queues
255
Dynamic Memory Allocation and Pointers
18 202 Lists and Iterators
........... 256
Dereferencing Pointers Quiz
202 261
Dynamic Memory Allocation Quiz Answers
204 262
A Game of 20 Questions
205
C++ Associative Containers and Algorithms
23 263
.........
Destructor Functions
209
Containers
263
Vectors: An Alternative to Dynamic Memory
Templated Functions
Allocation 268
209
Quiz
Quiz 273
210
Quiz Answers
Quiz Answers 274
211
Artificial Intelligence Algorithm for a Game
Object-Oriented Programming with Inheritance 24 275
19 213 ..........
.....
AI Game Playing
Inheritance 275
213
Developing Algorithms
The Protected Category 276
217
From Algorithms to Implementation
Constructors with Inheritance 278
220
Improving Your Algorithms
Quiz 280
224
Quiz
Quiz Answers 281
225
Quiz Answer
282
Object-Oriented Programming with Polymorphism
20 227
..
Glossary
283
A Class Hierarchy ...............................................
227
Virtual Functions
233
C++ Syntax
295
.............................................
Pure Virtual Functions
236
Symbols
Quiz 295
238
Predefined Keywords
Quiz Answers 301
240
Predefined Commands
303
Predefined Variable Types
304
Container Types
305
Bibliography
307
...........................................
iv
Table of Contents
Int roduction to C++:
Programming Concepts and Applications
As computers become more and more a part of our You then explore how the flow through a computer full support for OOP development. OOP typically
everyday lives, it is easy to imagine them as controlling program is managed, looking at the key concepts of involves 3 key ideas, each of which is explored:
our lives. However, programming gives us a chance to conditionals—where choices can be made (lecture )— encapsulation, where similar data and functions are
3
truly be in charge of the computers. Programming lets and loops, where commands can be repeated grouped together (lecture ); inheritance, where
16
us specify exactly how a computer should operate at the (lecture ). You also learn how to make use of the variables and functions are shared from one structure to
5
lowest levels. And by putting these low-level commands numerous functions that C++ provides in standard another (lecture ); and polymorphism, where different
19
together, we can get the computer to do complex and libraries (lecture ). structures can be used interchangeably (lecture ).
6 20
interesting things. OOP also brings up the idea of constructors, and
operator definitions are also commonly seen in OOP, so
Next, the course turns to structures that C++ provides
both of these ideas are addressed as well (lecture ).
This course explores the process of computer for handling larger amounts of data. You are introduced 17
Finally, though it is not an OOP-specific topic, the need
programming—specifically using the language C++. It to 2 methods: the array, a concept carried over from
to allocate and deallocate memory comes up frequently
is one of the most powerful programming languages the C language that forms the basis for storing data
in the context of OOP, so the idea of dynamic memory
there is, giving programmers the power to control from in a large block of memory (lecture ); and the vector,
7
allocation is explored (lecture ).
the lowest levels—specifying individual elements of a new approach in C++ that improves on the array 18
memory—to the highest levels, where broad concepts structure to provide additional safety and functionality
are used to manipulate large amounts of data. C++ also (lecture ). The way vectors are treated in C++ is The last major topic is generic programming,
8
supports a variety of programming paradigms, from very similar to the way it handles strings, which are emphasizing the use of the Standard Template Library
the traditional imperative and procedural approaches collections of characters used to handle text (lecture ). (STL) in C++. You discover key aspects of the STL and
9
that have long been a part of most languages, to the For large amounts of data, interactive input and output how using it can simplify your programming (lectures
object-oriented approaches that began to dominate is less feasible, so you are also introduced to the way and ).
22 23
programming in recent decades, to generic approaches that C++ can handle files (lecture ).
10
that let programmers specify behavior at an even more
Throughout the course, several lectures are
general level.
With these fundamental programming concepts interspersed that deal with the larger issues of how to
established, the course turns to the heart of procedural move from simply writing lines of code to developing
This course walks you through the range of C++ programming: the use of functions. Functions allow larger programs (lectures , , , , , and ). The
4 11 14 15 21 24
programming, providing a tour of all the key aspects of you to conceptually separate your program, making topics covered include methods of testing, incremental
programming in C++. No prior programming knowledge it feasible to develop much larger and more complex code development, debugging, exceptions, top-down
is assumed, and instructions are provided to help novice programs. You discover the process for writing your own and bottom-up design, and object-oriented design. The
programmers get everything set up to begin their functions (lecture ) and the different ways you can power of OOP is used to design a game engine that can
12
programming journey. handle parameters, including the introduction of the idea play different games (lecture ). The course concludes
21
of a reference (lecture ). with a final lecture showing how C++ can be used to
13
develop algorithms and in particular focuses on the way
The beginning lectures start with the basics of
an artificial intelligence algorithm can be implemented
programming, describing how variables work, how Following this, the course turns to object-oriented
as the opponent in a game (lecture ).
basic input and output is handled, and how basic programming (OOP). It's probably the most commonly 24
computations can be performed (lectures and ). used programming paradigm today, and C++ provides
1 2
1
Course Scope
01
Compiling Your First C++ Program
C++ is one of the most powerful, efficient, and flexible programming
IN THIS LECTURE:
languages that exists. It allows you to program in a way that closely
Introduction to Computer Programming
corresponds to machine instructions while also providing several
What Happens When You Program
higher-level features to make it easier for people to understand.
Your First Program
C++ supports multiple programming styles, or paradigms, that have
Program 1_1
emerged over time, and it is particularly strong in allowing you to use a
Program 1_9
variety of different paradigms in your programs. As a result, C++ is used
Program 1_10
as the basis for a wide variety of applications across many domains.
Quiz
Quiz Solutions
// INTRODUCTION TO COMPUTER PROGRAMMING
C++ has been used to develop many
Computers operate by following a set of that encodes the instructions and data
of the programs you've probably
instructions. But the instructions that a for a computer to use. For people, this is
experienced—from Microsoft
computer can understand are a bunch of 1s nearly impossible to follow, and this is why
and 0s—a long sequence of binary numbers programming languages have been developed. Windows to the code underlying
Google's search and to website
The first modern programming languages were
functionality on YouTube, Facebook,
developed in the 1950s, with Fortran being
What is sometimes considered the
Amazon, and PayPal. It's been used
the first widely used one. In fact, Fortran is still
first program was written in the
to control devices ranging from ship
used today! Fortran is a procedural language,
1840s by Ada Lovelace, who wrote
engines to Mars Rovers and in phone
and procedural programming is still a common
computational instructions that could
approach used today, including as a style of systems worldwide.
run, in theory, on a machine that had
C++ programming. Since Fortran, hundreds of
been designed but not built. languages have been developed, and each one
has its own strengths and weaknesses.
2
Lecture 01 | Compiling Your First C++ Program
In the 1980s, Bjarne Stroustrup wanted to One big advantage of C++ was that it added at a much higher level, using cutting-edge
retain the low-level efficiency advantages of the ability to do object-oriented programming, programming constructs that let you write
C while adding some of the more modern which lets you group your data and operations code once and apply that to a wide range of
programming approaches. Thus, C++ together in more useful ways. But C++ is applications.
was born! not only an object-oriented language. Other
new features have been added, too, allowing C++ is also a language that continues to be
C++ was developed as a sort of extension of it to reflect the most recent advances in developed today. There's a large and active
the programming language C, which itself programming language design. international C++ standards committee that
was a descendent of an even earlier language is continually working to determine ways to
called B. All of these came out of Bell Labs, This all makes C++ incredibly powerful, letting improve the language, including adding new
later known as AT&T Labs. While B never got you work across a full range of programming features that integrate the best and most
much use, C—which was developed in the paradigms. Like C, you can work in just recent programming practices.
early 1970s—became very widely used and still about as low a level of detail as you want,
is today. specifying individual bits, or you can work
As you go through this course, you'll
find it a much more rewarding and
// WHAT HAPPENS WHEN YOU PROGRAM valuable experience if you're able to
practice writing your own code. See
lecture 01b—C++ QUICK START.
Programmers generate a program written in or executed, by a machine. This compiled
a programming language, such as C++. The version of the program is called an executable
program is just a text file, and you're free to program, and you can then run it on your
write it in many different ways. You could use computer whenever you want.
your own word processor if you want and just
save it as a text file. You could use Notepad or As people develop code, they'll usually that code, have the compiler compile it into
WordPad on a PC or TextEdit on a Mac. There go through this process many times to machine language, and then run it—often just
are also editors written specifically to help see if it's working. To make it easier to with one click of a button.
people write code, such as Notepad++. develop code this way, programmers use an
integrated development environment (IDE), And there are usually other features built
Once you write a program, you send it to which will have an editor that lets you write into the IDE, such as a debugger, which is a
a compiler, which takes the instructions code, usually with some special features to tool that helps you find and fix errors in your
written in C++ and translates them into help you write code in that language. The IDE program. The IDE integrates all these things—
machine instructions—the instructions that will have an easy way to automatically save and more—into one package so that you can
the computer can understand. So, a compiled edit and compile and run and debug your
program is a program that's ready to be run, code all in one program.
3
Lecture 01 | Compiling Your First C++ Program
// YOUR FIRST PROGRAM
There's a very long-standing tradition in
// Program 1_1
computer science that the first program you
a
develop—in any language—is a
Hello, World!
// Our first program!
program, which is just a program that displays
A selection of programs will be shown
the message to the user.
Hello, World!
#include <iostream>
in this guide. To view all programs
b
discussed in this course, go to
Here's what a Hello, World! program looks using namespace std;
TheGreatCourses.com/CPlusPlus.
like in C++.
You set up an IDE and type the program into
int main()
the IDE's editor window. When you tell the IDE
c
to run the program, it will both compile the
{
program and then run the executable that the
cout << "Hello, World!" << endl;
compiler produced. The result of the program
is a line of output that prints out the words
}
.
Hello, World!
d
Curly braces are a critical part of
C++ programming that date all the
In programming terms, the word way back to a predecessor language
just means "display" or "show." in the 1960s called BCPL—and
print
The next line has and then a pair of
int main
before that to the way you write a
parentheses . This is the part of the code
(6)
that marks the beginning of the program—the set in mathematics, such as the set
The first lines you'll see are comment lines . main part. It lets the computer know that this
(a) containing the numbers {1,2,3}.
Comments are ways of giving notes about the is where the code you want to run begins.
code, but they do not affect what the code
actually does. Next, you'll see a pair of curly braces ,
(d)
which group a set, or block, of commands Finally, you have your actual line of code
The next few lines are header information together inside. In this case, the curly braces giving a command . This is the line of code
(8)
. The line gives you access to are grouping together all the commands inside that tells the computer specifically what you
(b) #include
a stream of input and output. The using of the main part of the program. want to do: It commands the output of Hello,
line makes it easier for you to . This statement is important; all the
namespace World!
write code. rest of this program is basically the same as in
other programs. This one statement is the key
line that does something specific.
4
Lecture 01 | Compiling Your First C++ Program