The examples in this book are all presented in C++. That’s the language I do most of my programming in, and it’s the language I’m most proficient in. That said, I’ve written a reasonable amount of Python, too—it’s the second-most used programming language at Sucker Punch. At the moment, we have about 2.8 million lines of C++ in our codebase and about 600,000 lines of Python.

If you’re a Python programmer, you don’t need to learn how to program in C++ in order to read the examples in this book. Code is code, basically—a loop is a loop, variables are variables, and functions are functions. There are some cosmetic differences, but the basic ideas in this book’s C++ examples translate pretty directly to Python, even when that translation isn’t immediately obvious!

This chapter is about explaining the translation. You won’t be able to write C++ code after working your way through this appendix—that’s at least a whole book’s worth of content—but you should be much more capable of reading it.

Types

Nothing like an example to show how straightforward reading C++ can be for a Python programmer! Here’s a simple function that calculates the sum of an array of numbers, first in Python:

def calculateSum (numbers):

    sum = 0

    for number in numbers:
        sum += number

    return sum

And then in C++:

int calculateSum(const vector<int> & numbers)
{
    int sum = 0;

    for (int number : numbers)
        sum += number;

    return sum;
}

It’s the same code, right? There’s some extra cruft in the C++ version, but the variables and the logic are the same.

As a Python programmer, you can pretty much ignore the curly braces and semicolons in this book’s examples. In C++, the curly braces and semicolons define sections of code, like indentation does in Python. Here, though, I’m also indenting the C++ to show sections, because that makes it easier to read; the curly braces and semicolons aren’t adding much value. 1

The most confusing bit of C++ for an old-school Python programmer is the types—the int and const vector<int>& syntax. These type annotations tell the C++ compiler what kinds of values to expect for the annotated variables or arguments—in this case, an integer and a list of integers. The compiler needs to know the types before it can actually compile the code.

There are types in Python, too, of course, even if the language doesn’t force you to worry about them. In Python the type details are usually sorted out when the code runs, not when it’s compiled. You can always call isinstance() to find out what the actual type is for an expression.

There are advantages to knowing about the types earlier in C++, most importantly that it helps you find bugs earlier, but specifying types does mean writing a bit more code. Python lets you skip some steps that C++ requires, which makes it easier to just write a little bit of code in Python.

Here’s how you can tell that both of these approaches are appealing: new versions of C++ let you skip the type annotations in lots of cases, and recent versions of Python let you add type annotations. Now you can write Python that looks more like C++:

def calculateSum (numbers: Iterable[int]) -> int:

    sum:int = 0

    for number in numbers:
        sum += number

    return sum

And C++ that looks more like Python:

auto calculateSum(const vector<int> & numbers)
{
    auto sum = 0;

    for (auto number : numbers)
        sum += number;

    return sum;
}

The examples in this book stick to “old-school” C++ and use explicit types. That’s our policy at Sucker Punch—we think it makes the code easier to read—so I’ve continued the practice here .

Formatting and Comments

Sometimes the overall structure of the code is the same in C++ and Python, but the syntax you’ll use to get there has more differences than in the first example. Here’s a function that shows up in Rule 1 —it merges two arrays into a single array by doing a riffle shuffle. 2 First, in Python:

# Riffle shuffle two lists into a single list by randomly
#  choosing a number from one list or the other until both
#  lists are exhausted

def riffleShuffle (leftValues, rightValues):

    leftIndex = 0
    rightIndex = 0

    shuffledValues = []

    while leftIndex < len(leftValues) or \
            rightIndex < len(rightValues):

        if rightIndex >= len(rightValues):
           nextValue = leftValues[leftIndex]
           leftIndex += 1
        elif leftIndex >= len(leftValues):
           nextValue = rightValues[rightIndex]
           rightIndex += 1
        elif random.randrange(0, 2) == 0:
           nextValue = leftValues[leftIndex]
           leftIndex += 1
        else:
           nextValue = rightValues[rightIndex]
           rightIndex += 1

        shuffledValues.append(nextValue)

    return shuffledValues

The algorithm is simple—choose a value from one list or the other until you’ve exhausted both lists, appending those values to a list of shuffled values. In C++ the same code looks like this:

// Riffle shuffle two lists into a single list by randomly
//  choosing a number from one list or the other until both
//  lists are exhausted

vector<int> riffleShuffle(
    const vector<int> & leftValues,
    const vector<int> & rightValues)
{
    int leftIndex = 0;
    int rightIndex = 0;

    vector<int> shuffledValues;

    while (leftIndex < leftValues.size() || 
           rightIndex < rightValues.size())
    {
        int nextValue = 0;

        if (rightIndex >= rightValues.size())
        {
            nextValue = leftValues[leftIndex++];
        }
        else if (leftIndex >= leftValues.size())
        {
            nextValue = rightValues[rightIndex++];
        }
        else if (rand() % 2 == 0)
        {
            nextValue = leftValues[leftIndex++];
        }
        else
        {
            nextValue = rightValues[rightIndex++];
        }

        shuffledValues.push_back(nextValue);
    }

    return shuffledValues;
}

Again, the structure of the code is the same. The two languages have the same basic features, so it’s easy to see how the various parts correspond to each other, but there are lots of small syntactic differences.

Comments

First, comments—there are a few ways to comment C++ code, but the examples in this book use a double forward slash to mark comments:

// Riffle shuffle two lists into a single list by randomly
//  choosing a value from one list or the other until both
//  lists are exhausted

Compare to Python’s hash comments :

# Riffle shuffle two lists into a single list by randomly
#  choosing a value from one list or the other until both
#  lists are exhausted

Indentation and Split Lines

Rules about splitting lines are different, too. In C++, all whitespace is considered equivalent. Spaces, tabs, and line breaks are interchangeable, so splitting the condition of the while loop across two lines requires no special syntax. You’re just exchanging a space for a new line:

while (leftIndex < leftValues.size() || 
       rightIndex < rightValues.size())

Line breaks are important in Python, so the two-line condition requires an explicit line continuation with a backslash:

while leftIndex < len(leftValues) or \
        rightIndex < len(rightValues):

Indentation is more free-form in C++, too, and that can take getting used to for a Python programmer. The actual grouping is defined by curly braces or semicolons—there’s no real meaning to the indentation. In this example, the two clauses are lined up in the same column, but that’s just to make the code easier to read.

Boolean Operations

Boolean operations are represented with symbols in C++. In this loop condition, C++ uses || where Python uses the much more straightforward or . In the same vein, C++ uses && for Python’s and , and ! for Python’s not .

Sometimes the two languages don’t line up exactly. The C++ function rand returns a random integer; this example checks whether that random integer is even or odd to randomly choose a source vector. The % character here calculates a modulo value, in this case 0 if the random value is even and 1 if it’s odd:

else if (rand() % 2 == 0)

In Python, the random module’s randrange function is used to do the same thing:

elif random.randrange(0, 2) == 0:

Lists

What Python calls “lists” are called “vectors” in C++. Python lists and C++ vectors work pretty much the same way, albeit with different names for everything. C++ uses the particularly lovely name push_back to append an item to the end of a vector:

shuffledValues.push_back(nextValue);

Python’s append is much clearer:

shuffledValues.append(nextValue)

You also use a size method on a C++ vector to get its length, rather than calling a global len function like Python does.

Increment Operators

Finally —wow, there were a lot of little details packed into this example—C++ has a syntactic shortcut for incrementing or decrementing a variable. This expression retrieves the leftIndex ’th value from leftValues , increments leftIndex , then puts the retrieved value into nextValue :

nextValue = leftValues[leftIndex++];

The same logic takes two lines in Python:

nextValue = leftValues[leftIndex]
leftIndex += 1

So, overall, lots of small differences, but everything in this C++ example has a pretty close analog in Python .

Classes

Both C++ and Python support classes, and the syntax for doing so isn’t all that different. The ways the two languages actually implement classes are very different, but that’s not important for the examples in this book. If you think of a C++ class as being like a Python class, where all of the instance attributes are set in __init__ , you’ll find the examples easy to follow.

Here’s a Python class implementing a 3D vector concept:

class Vector:

    _vectorCount = 0

    def __init__(self):
        self.x = 0
        self.y = 0
        self.z = 0
        self._length = 0
        Vector._vectorCount = Vector._vectorCount + 1

    def __del__(self):
        Vector._vectorCount = Vector._vectorCount - 1

    def set(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
        self._calculateLength()

    def getLength(self):
        return self._length
    
    def getVectorCount():
        return Vector._vectorCount

    def _calculateLength(self):
        self._length = math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)

Any 3D vector class is going to track three coordinates: x, y, and z. This particular class also caches the length of the vector and counts the number of vectors that currently exist. There’s no justification for the latter two features, by the way, other than illustrating a couple of syntactic differences between Python and C++.

Here’s the C++ equivalent:

class Vector
{
public:

    Vector() :
        m_x(0.0f),
        m_y(0.0f),
        m_z(0.0f),
        m_length(0.0f)
        { ++s_vectorCount; }
    ~Vector()
        { --s_vectorCount; }

    void set(float x, float y, float z);

    float getLength() const
    {
        return m_length;
    }

    static int getVectorCount()
    {
        return s_vectorCount;
    }

protected:

    void calculateLength();

    float m_x;
    float m_y;
    float m_z;
    float m_length;

    static int s_vectorCount;
};

void Vector::set(float x, float y, float z)
{
    m_x = x;
    m_y = y;
    m_z = z;
    calculateLength();
}

void Vector::calculateLength()
{
    m_length = sqrtf(m_x * m_x + m_y * m_y + m_z * m_z);
}

I’ve inadvertently demonstrated one of the benefits of Python here—Python is typically more concise than C++, with the Python version of this example clocking in at about half as many lines as the C++ version.

These two versions of the class have the same pieces, but those pieces are rearranged. Sometimes the rearrangement is obvious. In Python, the __init__ method is called when an object is created, and __del__ is called when the object is destroyed:

class Vector:

    def __init__(self):
        self.x = 0
        self.y = 0
        self.z = 0
        self._length = 0
        Vector._vectorCount = Vector._vectorCount + 1

    def __del__(self):
        Vector._vectorCount = Vector._vectorCount - 1

In C++, the class name itself is used for those two methods, with a prepended tilde ( ~ ) to mark the latter method. These two methods are called the constructor and destructor in C++ land. There’s also special syntax to initialize the instance variables:

class Vector
{
public:

    Vector() :
        m_x(0.0f),
        m_y(0.0f),
        m_z(0.0f),
        m_length(0.0f)
        { ++s_vectorCount; }
    ~Vector()
        { --s_vectorCount; }
};

Slightly different syntax is used for accessing the class’s variables. In Python, you need to be explicit about this with the self keyword:

class Vector:

    def getLength(self):
        return self._length

In C++, this is optional. You’re allowed to use this , C++’s equivalent to self , but the class’s variables are already in scope. The compiler can implicitly look up member variables for you:

class Vector
{
    float getLength() const
    {
        return m_length;
    }
};

If you see something in C++ that looks like a reference to a variable that hasn’t been defined yet, it’s probably a class variable .

Visibility

Python and C++ have different ways to manage the bits of internal logic that users of the class shouldn’t touch. In Python, there’s a convention to follow: start the name with an underscore. The Python example uses this for a class variable:

class Vector:

    _vectorCount = 0

There’s also a method:

class Vector:

    def _calculateLength(self):
        self.length = math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)

C++ solves the same problem with syntax, not conventions. The public keyword at the top of the Vector class marks what follows as being visible and usable to anyone with an instance of the object. The protected keyword, a bit further down, hides what follows from any code outside the class. As a result, users of the class can call the set method, but can’t call calculateLength . The calculateLength method can only be called from inside other Vector methods.

Class Vector
{
public:

    void set(float x, float y, float z);

protected:

    void calculateLength();
};

Declarations and Definitions

Next , let’s look at splitting a function’s declaration from its definition. In Python, all of a class’s methods are defined in the class itself:

class Vector:

    def set(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
        self._calculateLength()

    def getLength(self):
        return self.length

Many of the examples in this book will do the same thing in C++:

class Vector
{
public:

    float getLength() const
    {
        return m_length;
    }
};

In other cases, though, the examples will split the declaration of the method. First the code establishes that a method with a given name and type signature exists:

class Vector
{
public:

    void set(float x, float y, float z);
};

The function is then defined separately:

void Vector::set(float x, float y, float z)
{
    m_x = x;
    m_y = y;
    m_z = z;
    calculateLength();
}

These two forms are typically compiled differently in C++, with methods defined inside the class compiled inline , meaning that a separate copy of the function is generated and inserted wherever it’s called, while a single copy exists for functions with a separate definition. That’s not important for the examples in this book, though, so don’t worry about the distinction.

The last thing to point out in this example is how C++ deals with class attributes. In Python, class attributes are defined with statements in the class, and instance attributes are added in an __init__ method:

class Vector:

    _vectorCount = 0

    def __init__(self):
        self.x = 0
        self.y = 0
        self.z = 0
        self._length = 0

In C++, both class and instance attributes (or “members,” in C++-speak) are added in the class definition. The static keyword marks any class attributes; everything that isn’t marked with static is an instance attribute :

class Vector
{
protected:

    float m_x;
    float m_y;
    float m_z;
    float m_length;

    static int s_vectorCount;
};

Function Overloading

There are some features in C++ that don’t have direct analogs in Python. The converse is true, as well, of course—there are lots of Python features that C++ doesn’t have—but that’s unimportant here, since we’re focused on reading C++ code.

One thing that can be confusing to Python programmers is seeing two functions with the same name. Here’s an example in C++:

int min(int a, int b)
{
    return (a <= b) ? a : b;
}

int min(int a, int b, int c)
{
    return min(a, min(b, c));
}

void example()
{
    printf("%d %d\n", min(5, 8), min(13, 21, 34));
}

It’s not clear how this works—if you try to call the min function, which version is called? The C++ compiler makes this decision based on the arguments. If two integers are passed, it calls the first one; if three integers, it calls the second one. The example function prints 5 and 13 .

I snuck a useful bit of C++ syntax into the functions—the question mark operator, which lets you choose between two values based on an expression:

return (a <= b) ? a : b;

The Python equivalent to this is similarly funky:

return a if a <= b else b

For what it’s worth, this Python syntax confuses me every time I see it. So if you want to make a C++ programmer feel just a little bit clueless, make sure you add lots of ternary expressions to your code.

Templates

Another concept from C++ that has no Python analog is templates . To simplify things a bit: C++ templates are a way to write one chunk of code that handles multiple types. The compiler generates new code for each set of types used with the template.

The first example in this appendix summed an array of integer values. If you wanted to sum an array of floating-point values, you might write new code:

float calculateSum(const vector<float> & numbers)
{
    float sum = 0;

    for (float number : numbers)
        sum += number;

    return sum;
}

Or you might write a single version of calculateSum using templates and let the compiler do the work for you:

template <class T>
T calculateSum(const vector<T> & numbers)
{
    T sum = T(0);

    for (T number : numbers)
        sum += number;

    return sum;
}

The templated version of calculateSum will work for any type that implements the += operator and supports 0 as a value. That’s true for integers and floating-point values, but could also easily be arranged for other types. You could implement += and 0 for the Vector class from a few sections ago, for instance, and gain the ability to sum an array of Vector s.

In Python, there’s no need for any of this. The Python code I wrote to sum a list of values works perfectly well for any type that supports addition and initialization to 0:

def calculateSum (numbers):

    sum = 0

    for number in numbers:
        sum = sum + number

    return sum

When you see the C++ template syntax in the examples, it usually marks some bit of code that would work fine in Python without any templating at all .

Pointers and References

There’s one final thing that Python mostly hides from view but that C++ makes programmers worry about, and that’s passing arguments by value versus passing them by reference . In Python, simple types like numbers or strings are passed by value —a new copy is made whenever they’re assigned to a variable or passed as an argument to a function. It’s more complicated for types like lists or objects. Here’s an example:

def makeChanges (number, numbers):

    number = 3
    numbers.append(21)
    print(number, numbers)

globalNumber = 0
globalNumbers = [3, 5, 8, 13]

print(globalNumber, globalNumbers)
makeChanges(globalNumber, globalNumbers)
print(globalNumber, globalNumbers)

When this code is run it prints out:

0 [3, 5, 8, 13]
3 [3, 5, 8, 13, 21]
0 [3, 5, 8, 13, 21]

Notice how the simple value changes inside makeChanges to 3, then changes back to 0 when makeChanges returns, but the list changes without changing back. That’s because 0 was passed by value. A new copy was made when makeChanges was called. When makeChanges sets number to 3, it’s only changing the copy.

Python didn’t make a copy of the globalNumbers list—it just passed the original list. Both numbers and globalNumbers are holding onto the same list. When 21 is appended, it’s appended to that list. When you print numbers before returning or globalNumbers after, 21 shows up, because you’re printing the same list in both cases.

C++, by contrast, makes all of this more explicit. All variables and arguments are explicitly passed by value or passed by reference. The C++ equivalent to the preceding Python code looks like this:

void makeChanges(int number, vector<int> & numbers)
{
    number = 3;
    numbers.push_back(21);
    cout << number << " " << numbers << "\n";
}

The ampersand in front of numbers is important—it tells the compiler that this argument is passed by reference, not by value, so the compiler won’t make a copy of it when makeChanges is called. There’s no ampersand for number , so the compiler does make a copy of number .

If the ampersands are flipped, then the compiler makes a copy of numbers but not of number :

void makeChanges(int & number, vector<int> numbers)
{
    number = 3;
    numbers.push_back(21);
    cout << number << " " << numbers << "\n";
}

This version produces different output. Now it’s the simple value that is permanently changed, while the list pops back to its original value:

0 [3 5 8 13]
3 [3 5 8 13 21]
3 [3 5 8 13]

The examples in this book will often use references to avoid making expensive copies of bulky values. In most cases, the references will be marked with the const keyword to mark something that shouldn’t be altered, despite being passed by reference. That showed up (and was never explained) in the first C++ example in this appendix:

int calculateSum(const vector<int> & numbers)

With this usage, no copy is made of numbers , but the compiler won’t allow any changes to numbers either. In practice this is really similar to passing it by value, but at much lower cost.

As a final note, in a few cases the examples use the other (sigh) C++ syntax for passing things by reference— pointers . Pointers and references are almost exactly the same thing, and the differences aren’t really important if you’re just trying to figure out what the code is doing. The key syntactic differences are:

  • Pointers are defined with * instead of & .

  • Pointers use -> instead of . to get at members.

  • To convert a pointer to a reference, you use * ; to convert a reference to a pointer, you use & .

Here’s the example code written with pointers :

void example(int number, vector<int> * numbers)
{
    number = 3;
    numbers->push_back(21);
    cout << number << " " << *numbers << "\n";
}

void callExample()
{
    int number = 0;
    vector<int> numbers = { 3, 5, 8, 13 };
    cout << number << " " << numbers << "\n";
    example(3, &numbers);
    cout << number << " " << numbers << "\n";
}

This book’s examples use constant references whenever an argument is conceptually being passed by value, but actually passing the argument by value would be expensive. In all other cases, pointers are used.

1 That’s why Guido ditched them.

2 Like a deck of cards. Or poker chips, if you’re trying to look like a professional poker player.