Chapter 2: From Python to C++#
In this chapter, we will introduce fundamental concepts in C++ by seeing how elements from Python such as variables, flow control and functions look like in C++. In the end, we will look at more complex comparative examples. It should be stressed that there are fundamental paradigmatic differences between C++ and Python, not just at the syntactic level. While two different programs written in C++ and Python might have the same behaviour or outputs, they operate differently under the hood.
First Things First…#
Before we can jump into programming in C++, we need to cover some fundamental points neccesary for actually running any C++ code. Consider the following, very simple code in Python.
1x = 2
2y = 4
3z = x + y
4print(f"The sum of {x} and {y} is {z}")
If we were to translate this into C++, it would look something like the following.
1#include <iostream>
2using namespace std;
3
4int main()
5{
6 int x = 2;
7 int y = 4;
8 int z = x + y;
9 cout << "The sum of " << x << " and " << y << " is " << z << "\n";
10
11 return 0;
12}
Let’s go line by line to understand the elements introduced by C++ in this example:
Line 1-2:
The
#include <iostream>
is called a preprocessor directive. Think of this asimport
in Python. In this case its “importing”iostream
, which is part of the standard library and includes tools to read and write text to/from the console such ascout
andcin
.In C++, code is organized into namespaces. In practice, this allows us to have functions with the same name. For instance, I could have a namespace called
space1
and anotherspace2
, both of which have a function defined within them calledfunc
and I could use them both in my code by specifying which namespace I am referring to when I call the functionfunc
.space1::func(); space2::func();
By specifying that we are using the namespace
std
, we avoid having to specifying thatcout
, which is part of thestd
namespace, indeed comes from said namespace. If line 2 was not there, we would need to writestd::cout
.
Line 4
This line is a function header for a function called
main
which we indicate will return a value of typeint
. This function is fundamental because every C++ program starts by running themain
function.Unlike in Python where we indicate that a set of statements are part of a function by indenting them with respect to the function header, in C++ we indicate this by having these statements enclosed by
{}
.
Lines 5 to 10
These lines define the body of the function
main
.Notice that each statement ends in
;
. This tells the compiler that that is the end of that particular statement. This is neccesary to add because, unlike Python, C++ is a whitespace-independent language which means that the following two snippets of code are completely equivalent to the compiler and thus, without;
, there would be no way for the compiler to know that it had reached the end of a statement[1].int main() { int x = 2; int y = 4; return 0; }
int main(){int x=2;int y=4;return 0;}
We will discuss the rest of the elements seen in the code snipper as we go along, but take some time to try to deduce what each part is doing.
Variables and Types#
Basic Types#
In Python, if you want to define a variable of type int
you simply need to write x = 2
, and the interpreter will infer the type. This is because Python is a dynamically typed language, which means that type checking and type assignment of variables happens at runtime and the type of a variable will be based on the value assigned to it. This also means that we can declare a variable to have a value of a particular type, but then assign it a value of a different type. For instance, the following is valid in Python.
x = 2
x = "This is a string!"
C++, however, is a statically typed language. This means that type assignment and checking is done at compile time and that, when we declare a variable, we must specify its type and that this type is unchanging. Thus the following works
int x = 5;
x = 6;
but this will cause an error when you attempt to compile
int x = 5;
x = 0.45; // Not an integer!
Note that, just like in Python has some reserved keywords which you would not want to name your variables (e.g. print
is a terrible name for a variable!), C++ also has a set of reserved names. For instance, if you try to call a variable return
, the compiler will complain. You can ready more about these reserved keywords here. In addition to these restrictions, C++ has other rules for what variable names are valid. In order for an identifier to be valid, it must obey the following conditions:
It must be a sequence of one or more letters, digits, or underscore
It must NOT include spaces, punctuation marks & symbols
It must ALWAYS begin with letter or underscore (though the latter is usually reserved for special purposes)
It must NOT be one of the reserved keywords in C++
The following table shows some of the data types found in C++ which you might find most familiar having some knowledge of Python. Note that there are more data types than these which we will see later, but these will at least get you started.
Type |
Keyword |
Example value |
---|---|---|
Boolean |
bool |
True |
Character |
char |
“c” |
Integer |
int |
64 |
Floating point |
float |
3.14 |
Double floating point |
double |
6.15 |
Valueless |
void |
n/a |
String |
std:string |
“Hello World!” |
In C++ we also have arrays. An array is a series of elements of the same type (thus occupying the same amount of memory) in a contiguous memory location. Each of them can be refereced with an index.
Arrays & Vectors#
An array, the C++ equivalent of a tuple in Python, is a series of elements of the same type (and thus each occupying the same amount of memory) in a contiguous memory location. Just like with tuples in Python, each element can be refereced with an index. So, for example, while in Python we might have something like the following
tuple_of_nums = (14, 15, 16, 17)
num1 = list_of_nums[1]
print("The second number in the tuple is: ", num1)
In C++, we would have something like this instead
1#include <iostream>
2using namespace std;
3
4int main()
5{
6 int arr_of_nums[] = {14, 15, 16, 17};
7 int x = arr_of_nums[1]; // Value 15 is copied and assigned to x
8 cout << "The second number in the array is: " << x << endl;
9}
Here, we are defining an array arr_of_num
which we tell the computer will have elements of size int
(usually 4 bytes). In additional, we are initializing the array with some integers. Note that when we assign arr_of_nums[1]
to x
, what happens is that the value is copied and assigned to x.
Warning
Unlike in Python, in C++ it is possible to use an out of bounds index when fetching an element from an array. This is because when you do int_arr[n]
all your computer is doing is finding the space space in memory sizeof(int) * n
away from int_arr[0]
, which can go beyond the actual space alloted for the array. To see this in action, run the following code. Your compiler might complain, but if it does indeed compile, you see that what is printed to the console is junk because we are accessing some random piece of memory. Do this at your own risk and, in practice, try to never do it! You could break something or cause your program to behave unexpectedly.
One limitation with arrays is that the size of the array is unchangeable[2]. However, C++ offers an alternative called vectors which are dynamic arrays that can change in size, making them the Python equivalent of lists. So, for example, in Python we might have something like the following
lst_nums = [14, 15, 16, 17]
lst_nums.append(18) # Adding an element to the list
print("Added element", lst_nums[4])
Whereas, in C++, using vectors we would have:
1#include <vector>
2#include <iostream>
3using namespace std;
4
5int main()
6{
7 vector<int> vec = {14, 15, 16, 17};
8 vec.push_back(18);
9 cout << "Added element: " << vec[4] << endl;
10}
where push_back
is the C++ equivalent of append
.
Warning
If the above example does not compile for you, it might due to the way we are initializing the vector, which is only compatible with C++11 or later. To fix this, add -std=c+11
when you go to compile, or use the included extra example, examples_cpp/c2_vectspushbackold.cpp
which does not use this way of initializing.
Statements & Control Flow#
In Python, we have the well known flow control statements if-else
statements, while
loops, etc. All of these are used to allow us to repeat operations in our code or to allow it to branch depending on some pre-defined conditions. C++ also has its own control flow statements, many of which will be familiar to you. To get started, in the table below, we present a summary of the main control flow statements in C++. In the subsequent sub-sections, we will cover the most basic and useful of these by starting with a Python example at first, and then seeing the equivalent in C++.
Category |
Meaning |
Implemented in C++ by |
---|---|---|
Conditional statements |
Set of statements will only be executed if a condition is met. |
|
Jumps |
Start executing statements at another location |
|
Function calls |
Jumps to another location and back |
functional calls, |
Loops |
Repeatedly execute a set of statements until some condition is met. |
|
Halts |
Terminate the program |
|
Exceptions |
Error handling |
|
if-else
#
In Python, we might have something like the following
1x = 10
2if x > 5:
3 print("x is greater than 5")
4elif (x <= 5) and (x >= 0):
5 print("x is in between 5 and 0 (inclusive)")
6else:
7 print("x is negative")
In C++, the equivalent would be:
1#include <iostream>
2using namespace std;
3
4
5int main ()
6{
7 int x = 10;
8 if (x > 5)
9 {
10 cout << "x is greater than 5 \n";
11 }
12 else if ((x <= 5) && (x >= 0))
13 {
14 cout << "x is in between 5 and 0 (inclusive) \n";
15 }
16 else
17 {
18 cout << "x is negative \n";
19 }
20}
for
#
In Python, we might iterate over a list like this:
1for i in range(10):
2 print(i)
In C++, the equivalent for
loop woudl be:
1#include <iostream>
2using namespace std;
3
4int main ()
5{
6 for (int i = 0; i < 5; ++i)
7 {
8 cout << i << "\n";
9 }
10}
while
#
A Python while
loop might look like this:
1i = 0
2while i < 5:
3 print(i)
4 i += 1
In C++, the same logic would be:
1#include <iostream>
2using namespace std;
3
4int main ()
5{
6 int i = 0;
7 while (i < 5)
8 {
9 cout << i << "\n";
10 ++i;
11 }
12}
do-while
#
Python does not a have a direct implementatinon of do-while
loops. However, we can create the logic. It would be as follows:
1i = 0
2
3while True:
4 print(i)
5 i += 1
6 if i > 25:
7 break
In C++, this same logic would look like
1#include <iostream>
2using namespace std;
3
4int main ()
5{
6 int i = 0;
7 do
8 {
9 cout << i << "\n";
10 ++i;
11 } while (i <= 25);
12}
break
& continue
#
break
and continue
work in the exact same way in C++ as they do in Python. For instance, in Python we might have something like this:
1max_num = 10000
2
3for i in range(max_num):
4 if i == 50:
5 break
6 if i % 2 == 0:
7 continue
8 print(i)
9
10print("End of loop!")
In C++, the same code would look like this:
1#include <iostream>
2using namespace std;
3
4int main ()
5{
6 int max_num = 10000;
7 for (int i = 0; i < max_num; ++i)
8 {
9 if (i == 50)
10 {
11 break;
12 }
13 else if (i % 2 == 0)
14 {
15 continue;
16 }
17 cout << i << endl;
18 }
19 cout << "End of loop!\n";
20}
switch
#
If you have a fixed set of possible ramifications that you want your code to go down, the you would use switch
. They are equivalent to a set of if-elif-else
statements in Python, but they are not directly implemented. For instance, in Python, we might have the following:
1print("""
2What is your favortie color (input the number):
3 1. Red
4 2. Blue
5 3. Green
6 4. Yellow
7""")
8
9user_input = int(input())
10
11if user_input == 1:
12 print("You must like apples!\n")
13elif user_input == 2:
14 print("You must like looking at the sky!\n")
15elif user_input == 3:
16 print("You must like vegetables!\n")
17elif user_input == 4:
18 print("You must like looking at the Sun! (And you should probably stop...)\n")
19else:
20 print("I've never heard of that color...:(\n")
In C++, we could implement this rather easily with if-else
statements, but it can be done more straightforwardly using switch
. The following snippet is the C++ translation of this.
1#include <iostream>
2#include <string>
3using namespace std;
4
5int main()
6{
7 int input;
8 cout << "What is your favorite color (input the number):\n";
9 cout << "1. Red \n2. Blue\n3. Green\n4. Yellow\n";
10 cin >> input;
11
12 switch (input)
13 {
14 case 1:
15 cout << "You must like apples!\n";
16 break;
17 case 2:
18 cout << "You must like looking at the sky!\n";
19 break;
20 case 3:
21 cout << "You must like vegetables!\n";
22 break;
23 case 4:
24 cout << "You must like looking at the Sun! (And you should probably stop...)\n";
25 break;
26 default:
27 cout << "I've never heard of that color... :(\n";
28 }
29 return 0;
30}
Functions#
Functions in C++ work very similary to how they work in Python. However, there are some additional complications regarding memory and how values are passed to them which will be discussed later on. For now, we can familiarize ourselves with functions by seeing how they are structured in both Python and C++. In Python, we may have a function like the following.
1def add(a, b):
2 return a + b
3
4result = add(3, 4)
5print(result)
In C++, the equivalent function would be:
1#include <iostream>
2using namespace std;
3
4int add(int a, int b) {
5 return a + b;
6}
7
8int main() {
9 int result = add(3, 4);
10 cout << result << endl;
11 return 0;
12}
Classes#
Classes in both Python and C++ allow you to create user-defined data types with attributes (data members) and methods (member functions) to manipulate these attributes. In Python, we could write a class like in the following example.
1class MyClass:
2 def __init__(self, value):
3 self.value = value
4
5 def display(self):
6 print(self.value)
7
8obj = MyClass(10)
9obj.display()
In C++, the same class can be written like this:
1#include <iostream>
2using namespace std;
3
4class MyClass {
5 public:
6 // Constructor, equivalent of __init__ in Python
7 MyClass(int val) : value(val) {}
8
9 void display() {
10 cout << value << endl;
11 }
12 private:
13 int value;
14};
15
16int main() {
17 MyClass obj(10);
18 obj.display();
19 return 0;
20}
In this example, it is evident that C++ has some additonal elements not seen in Python. Firstly, we see the access specifiers public
and private
which dictate how the access permissions of the member attributes and methods. Here is what they mean:
public
: Members are accessible from outside the classprivate
: Members are accesible only inside the class.
Note that although you can indicate in Python that a member function/attribute is public or private by, for instance, including underscore characters at the beggining of the variable name (e.g _private_var
) and not including these characters for a public attribute (e.g.public_var
), these are just conventions and the language itself does not enforce this distinction. In C++, however, this distinction is enforced and thus a protected variable cannot be accessed outside the class.
You might also notice the line in the class in C++: MyClass(int val) : value(val) {}
. This is a special method called the constructor and its job is to perform initializations, similar to how __init__
works in Python. The name of the constructor is always the same as the name of the class itself, and the syntax is as follows:
ClassName(typevar1 var1, typevar2 var2) : classattrib1(var1), classattrib2(var2) {}
In the constructor, classattrib1(var1)
is part of the initializer list, which initializes the class attributes classattrib1
and classattrib2
with the values passed as parameters var1
and var2
.