A short introduction to C++ - basic

Part 0. Setting up C++

OS: Linux / Mac OS / WSL

We are going to have two windows open at the same time:

  1. A text editor (vi, emacs, vscode etc).

  2. The command line or terminal, where a C++ compiler has already been installed and is working.

1. Getting ready

  1. Create a new directory called cpp:

  2. In this chapter, every example can be compiled with:

  3. Then run with:


Part 1. Hello world!

2. Hello world!

For cin, cout, endl stuff, we need the <iostream> library. Libraries are like toolboxes.

return 0; in the main function means the program executed successfully.

3. Use of variables

4. Command-line input

5. Maths

6. If

7. For and while loops


Part 2. Files, arrays and functions

8. Saving and reading data

To save and read files, we need to include the <fstream> library.

Your turn:

Note: this version uses while (myfile >> x[count] >> y[count]), which is safer than checking eof() first.

9. Arrays

10. Functions

Writing functions allows us to do more complicated things.


Part 3. Pointers, arguments and classes

11. Pointers

12. Main function with arguments

If you want to access command-line arguments, you can declare main() as follows.

Typical output:

This form will be useful later when you want to read input files and write output files from the terminal.

13. Classes

Classes are one of the main things that separate C++ from C. Classes are ways for us to set up objects that have properties and functions which are particular to that type of object. A class is something like a user-defined data type.

If you want to use Rectangle in many files, it is annoying to define it every time. In actual usage, the declaration of the class usually goes into a header file, and the definitions of member functions go into a source file.