1. Introduction to C++#
Bjarne Stroustrup developed the initial versions of the C++ programming language starting in 1979. Originally, the language was designed (and called) as “C with Classes”. Overtime, the language has become an international standard with the most recent adoption in 2020. As background, C was created in the early 1970’s by Dennis Ritchie at Bell Labs. As a general-purpose computer programming language, C has found long-term use in operating systems, device drivers, and embedded systems. Due to its small size, the language has been ported to just about every platform imaginable. C has also widely influenced many other languages: C++, Java, JavaScript, and others. The primary Python interpreter is written in C. Many of Python’s popular APIs, such as NumPy, are developed in C with a language binding to Python.
Over the decades, C++ has matured and evolved, adapting to modern programming paradigms and needs, yet it has always retained its roots in C, giving it a unique blend of procedural and object-oriented programming capabilities at varying abstraction levels.
Michael H. Goldwasser and David Letscher have written an excellent guide to transition from Python to C++. While it uses Python 2.x, you should not have any difficulty making the changes mentally for the Python 3.x syntax.
1.1. Key Features and Characteristics of C++:#
Object-Oriented: C++ contains the concepts of classes and objects, encapsulation, inheritance, and polymorphism, making it easier to model and manage complex software system.
Performance: C++ is known for its high performance, primarily because it provides low-level memory access and does not impose much overhead, as might be seen in purely interpreted language.
Statically-Typed: C++ is a statically-typed language, meaning type checking is done at compile-time rather than run-time. This helps catch many types of errors before the program
Direct Access to Memory: Through pointers, C++ allows direct access and manipulation of memory, providing fine-grained control that can be critical in systems programming and high-performance appli Modern C++ provides facilities to make the use of pointers safer than the initial iterations of the language and the base C language.
Feature-Rich Standard Library: The C++ Standard Library provides a comprehensive set of functions, classes, and templates for tasks ranging from string manipulation and file I/O to containers and algorithms.
Platform-Dependent and Platform_-Independent: While C++ code can be written in a platform-independent manner, it also allows developers to write platform-specific code when necessar7. Extensibility: C++ provides features that enable language extension and powerful metaprogramming, such as templates.
Compatability with C: C++ maintains a high degree of compatibility with C, allowing most C programs to be compiled as C++ with little to no modification. However, the backwards compability has increased the complexity of the languaged with multiple keywords and ways to accomplish the same task.
With its rich features and legacy, C++ has found applications in various domains, from developing operating systems, game engines, high-frequency trading platforms, to embedded systems and more. As the technology landscape continues to evolve, so does C++, with modern features and improvements being added to make it relevant, powerful, and user-friendly for current and future generations of programmers.
1.2. The First Program#
Many programming books and tutorials tend to start with a simple program for several reasons:
simple, yet reable example.
being able to run the program successfully demonstrates that -
you can compile the the progam
you can execute the program
you can see the outIput
Immediate feedback
Kernighan and Ritche used “hello, world” in the The C Programming Language.
Below is the typical “Hello World” program in C++ along with a countdown to demonstrate a for loop.
1//filename: hello.cpp
2#include <iostream>
3using namespace std;
4
5int main(int argc, char *argv[]) {
6 cout << "Hello World\n";
7
8 int countdown = 5;
9 for (int i = countdown; i >= 0; i--) {
10 cout << i << "\n";
11 if (i == 0) {
12 cout << "Let's go!" << endl;
13 }
14 }
15 return EXIT_SUCCESS;
16}
Depending on whether or not you have a C++ kernel installed for Jupyter, you may or may not be able to directly execute the C++ programs in the notebook. As a work-around, you should open a terminal window and place it below the notebook so you can execute commands to complile and run the programs along with providing any necessary input from console.
Every code progam in these notebooks will have the program name in a comment as the first line.
The file extension is “.cpp” to signify a C++ source file.
Programmers typically use “.hpp” or “.h” for C++ header files. For these class, we will use “.hpp” as the suffix clearly delineates the file’s usage as containing C++ code.
To compile the program, use g++
. For this class, we will use the flag -std=c++17
to specify the 2017 C++ Standard:
g++ -std=c++17 hello.cpp
In later notebooks, we will introduce additional compilation flags to check for various warnings and bad practices.
By default, g++ compiles the program to an executable called “a.out”. To execute that program, run ./a.out
.
$ g++ -std=c++17 hello.cpp
$ ./a.out
Hello World
5
4
3
2
1
0
Let's go!
The leading “./” is necessary when the current working directory is not part of the PATH variable, which many
operating systems use to find executables. In the terminal, you can display the current working directory by
executing pwd
. To see the contents of the PATH
variable, execute echo $PATH
.
To specify a different output name, use the -o name option in g++: g++ -std=c++17 -o hello hello.cpp
Then, you can execute the program with ./hello
1.3. hello.cpp Walkthrough#
Note: The line numbers correspond to the actual line numbers of the file hello.cpp.
On line 2, we include the C++ library for performing input/output. This library has been designed to abstract how Linux/Unix treats files, devices, and network connections as streams of information. The include mechanism is similar to import in Python.
Line 3 allows us to access the names declared in the std namespace directly. Rather than the flat namespace that C contains, C++ also allows us to organize classes into namespaces. We can address classes, functions, and variables in that namespace by using the namespace name followed by the operator ::(scope resolution operator). With the “using” clause” we can access the standard output stream by using cout rather than
std::cout
. With Python, the equivalent would befrom packageName import *
. Generally speaking, you will want to minimize your use of importing namespaces to avoid naming conflicts.Line 5 is the start of the main() function. With C++, all programs require a main function. The signature of this main function can differ slightly, but in this example, we show how to make available command-line arguments to the program.
Rather than using a
:
followed by an indented code to represent code blocks, C++ uses curly braces{
}
for code blocks.Line 6 places the “Hello World” string onto the standard output stream, cout, followed by the newline character, the \n escape sequence (either in a string or as a character). In line 11, we use a stream manipulator token, endl. This token represents a newline and then flushes the stream - forcing all outputs to be sent.
Bjarne Stroustrup has stated that the “c” in cout stands for “character” because iostreams map values to and from byte (char) representations. Others substitute “console” for the “c”. The
<<
stream insertion operator points in the direction where data is being sent. In this case data is being sent to standard output (cout).C++ ends statements with a semicolon
;
, whereas Python typically uses newlines.In Python, we create variables by assigning a value to a particular name. Implicitly, that defines a type (e.g., str, int, list, etc.) for that variable. Within C,++ we must explicitly declare variables of a particular type before their use. In line 7, we declare countdown as a variable with type
int
and immediately initialize the variable (assign to it), the value of 5.Rather than everything being an object as in Python, C++ uses primitive types in addition to objects.
In line 9, we declare a for loop. Rather than iterating over a sequence of items (e.g., a list, tuple, lines (from a file), or string) in Python, this for loop is closer to what we have when using the for loop with range(). In C++, this control structure is composed of three parts: an initializer(
int i = countdown
), a check that runs before each iteration of the loop (i >= 0
), and then a statement that runs at the end of each loop (i--
).Line 11 demonstrates an
if
statement. Again, we have slightly different syntax. C++ requires the expression to be contained within parenthesis. C++ includes a bool type. However, boolean values can also be represented by a value of 0 for false and any other value for true.Finally, in line 15, the program returns
EXIT_SUCCESS
(i.e., 0) back to the calling process. As with Python andsys.exit()
, 0 indicates success
1.4. C++ Highlights#
The following sections highlight some of the initial differences from C++ as compared to C and Python. As C++ supports object-oriented programming, the language also provides support for classes and templates. The input/output mechanisms have also changed, although you can technically use C’s facilities as well (this is discouraged, but C++ has considered interoperability with C during its development). C++ also provides additional mechanisms for memory management.
1.4.1. Variable Initialization#
With C++, multiple ways exist to initialize variables. The standards committee added uniform (brace) initialization in the C+11 standard. While it solves many problems, the solution also created other issues which are now being addressed in the C++23 standards process. The follow declarations are equivalent:
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
int a = 1;
int b(2);
int c{3};
cout << a+b+c << endl;
}
Some recent recommendations (including the C++ Core Guidelines have been simply to use the the {} method as much as possible. However as this blog post highlights, that presents both readability and semantic challenges. Some recommendations:
Use = whenever you can.
Use initializer-list syntax {} only for element initializers (of containers and aggregates).
Use function-call syntax () to call a constructor that functions as a factory method.
Don’t panic! As you gain more experience, you will also gain the knowledge of when the use the appropriate initializer.
1.4.2. Booleans#
C++ does have a built-in data type, bool, to represent booleans. true and false are special keywords that function as constants to represent 1 and 0, respectively. The operators are the same as those in C. Notice that the literals differ slightly from Python by not being capitalized.
1//filename: boolean.cpp
2//compile: g++ -std=c++17 -o boolean boolean.cpp
3//execute: ./boolean
4#include <iostream>
5using namespace std;
6
7int main(int argc, char *argv[]) {
8 bool t = true;
9 bool f = false;
10
11 cout << "True: " << t << "\n";
12 cout << "False: " << f << "\n";
13}
1.4.3. Functions#
Over Python, C++ adds the ability to overload functions - that is to have the same function name, but with different number of parameters and/or types. Python simply replaces the function. Over C, C++ allows default parameter values.
1//filename: function.cpp
2//compile: g++ -std=c++17 -o function function.cpp
3//execute: ./function
4#include <iostream>
5using namespace std;
6
7int max(int a, int b) {
8 cout << "int max called: ";
9 if (a > b) { return a; }
10 else { return b; }
11}
12
13double max(double a, double b=0) {
14 cout << "double max called: ";
15 if (a > b) { return a; }
16 else { return b; }
17}
18
19int main(int argc, char *argv[]) {
20 cout << max(42, 39) << "\n";
21 cout << max(2.72, 3.14) << "\n";
22 cout << max(-3.14) << "\n";
23}
1.4.4. Input Sample#
The following code example allows users to enter a stock name and its corresponding price. You’ll need to run the program in a terminal window. If you use a string for the price, the input stream produces an error and places 0 into the price variable.
1//filename: input.cpp
2//compile: g++ -std=c++17 -o input input.cpp
3//execute: ./input
4#include <iostream>
5using namespace std;
6
7int main() {
8 cout << "Please a stock name and price: ";
9 string name; // string variable
10 double price = -1.0; // double variable
11 cin >> name; // read a string
12 cin >> price; // read the price into a double
13
14 if (price > 0) {
15 cout << name << " has a stock price of $" << price << "\n";
16 }
17 else {
18 cout << "Invalid price entered for the stock: " << name << "\n";
19 }
20}