Introduction to C++

Tips for navigating the slides:
  • Press O or Escape for overview mode.
  • Press the copy icon on the upper right of code blocks to copy the code

Class outline:

  • C++
  • Variables
  • Types
  • Functions

C++

Overview

C++ is a language derived from the C programming language.

C++ has good support for Object-Oriented programming.

C++ has poor support for Higher-Order Functions and zero support for lambda functions.

C++ allows code to manipulate memory (both powerful 💪🏽 and dangerous 🤕).

C++ is fast

Why to care? C++ is used in the next two CS courses:

  • CS 235 Data Structures
  • CS 236 Discrete Structures

Compiled Language

Unlike Python, which is interpreted, C++ is compiled down to the machine language and the executed directly by your Operating System (OS).

In CS 235, you will learn how to compile C++ programs. For this course, we'll use an online compiler (the compiling and execution process happens on some server out on the web).

There is an online compiler option here: https://www.w3schools.com/cpp/cpp_compiler.asp

Statically Typed Language

Python is dynamically typed (sometimes called untyped, but this term is misleading)

  • Python only requires the type to be checked when used in an operation or to call a method at the time of interpretation

C++ is a statically typed language, which means that all data must have a known type before the program is compiled

  • Types are explicitly stated for both variable and function declarations
  • All types for all data and operations must be checked before any code is run

Statements and Scope

In Python statements don't have any special ending.

But in C++ all statements must end with a semicolon ;

In Python scope is determined by indenation.

But in C++ scope is denoted with braces{ }

Variables

Type Restriction: Python vs C++

In Python we can change the type of the value bound to a name.


                        x = 14     # note there is no type or semicolon
                        type(x)    # <class 'int'>
                        x = 'hi there'
                        type(x)    # <class 'str'>
                    

The above is not allowed in C++. Once we create a variable of type int called x, x can only be assigned values of type int.

Note: only values have types in Python, but in C++ both names and values have types

Creation: Python vs C++

In Python all variables are just a name bound to some value.


                        x = 14     # note there is no type or semicolon
                        type(x)    # <class 'int'>
                    

In C++ all variables must be given an explicit type before the variable name.


                        int x = 14;    // note the semicolon
                    

Types

Built-in Types: Python vs C++

Here are the built-in types we've used with Python:

  • Integers
  • Floats
  • Booleans
  • Strings
  • Lists
  • Dictionaries

C++ only has 3 of these 6 types built-in:

  • Booleans
  • Floats
  • Integers

Built-in Types

What?!? 😨

C++ doesn't have built-in strings, lists, or dictionaries?

  • C++ has two types of strings
  • C++ uses arrays instead of lists (also has a vector class this is similar)
  • C++ does not have a dictionary type (but does have a map class that is similar)

We will see vectors and maps in detail later.

Boolean Type

The C++ boolean type is bool and has values true and false.


                    bool repeat = true;
                    

There is no third boolean type in C++ (like None in Python).

Float Types

There are two floating-point types in C++: float and double.

double has double the precision (twice the storage size) as float.

Common practice is to always use double when on a PC (float is usually only used on embedded devices with restricted memory).


                    
                    float grade = 0.85;
                    double rate = 1.3;
                    

Integer Types

C++ has multiple integer types that can hold numbers of different bit sizes.

C++ has both signed and unsigned integer types

  • signed types are numbers that can be both positive and negative
  • unsigned types are numbers that can only be non-negative, always >= 0

Integer Type Sizes

C++ integers have sizes that can vary, depending on the processor for which the code is compiled 🤯

Type Signed/Unsigned Size in Bits
short int Signed at least 16
unsigned short int Unsigned at least 16
int Signed at least 16 (often 32)
unsigned int Unsigned at least 16 (often 32)
long int Signed at least 32
unsigned long int Unsigned at least 32
long long int Signed at least 64
unsigned long long int Unsigned at least 64

int Type

In practice, usually only int and unsigned int are used.

int is often 32 bits, so it contains the numbers in the following range -2^31 through 2^31-1 or -2,147,483,648–2,147,483,647

unsigned int has a range from 0 through 2^32-1, or 0–4,294,967,295

The unsigned integer type is used when a variable should only store a non-negative number (like the size of something), but we often just use int for most numbers.


                        int year = 2022;
                        int month = 4;
                        int day = 1;
                    

Strings

C++ has a string type called C-strings which come from the C programming language

  • Start and end with ", i.e. "hi there!"
  • Mutable (this can be dangerous⚡)
  • Cannot use single quotes ' ' like in Python

C++ has a string type that is a class called string that comes from the C++ Standard Library

  • Can be assigned with a C-string literal
  • Immutable
  • More similar to Python string

                        // variable is type `string` and value is type `C-string`
                        string name = "Grace Hopper";
                    

String Methods

Here are some common methods provided by the string class:

Method Parameter(s) Description
at int — index Accesses the specified character with bounds checking
front (none) Accesses the first character
back (none) Accesses the last character
c_str (none) Returns a immutable C-string version of the string
empty (none) Returns true if string is empty, false otherwise
size/length (none) Returns an unsigned integer type with length of string

Many, many more. See C++ Reference.

Importing Strings

The C++ Standard Library provides the class string that is similar to Python's str

You must import this class in C++ style (at the top of your file):


                    #include <string>
                    

Since the string class is in the Standard Library, you need to use std:: before the name string.


                    std::string nasaEmployee = "Katherine Johnson";
                    printf("The third character in the string is: %c", nasaEmployee.at(2));
                    

Arrays

C++ arrays are a an ordered group of contiguous memory addresses. The square brackets [ ] are used to denote arrays.

To define an array type, the type for all elements must also be explicit; the size of the array must also be given.

Here is code to create a variable of type array of integers:


                    // now the name 'values' is a variable that stores ten integers
                    int values[10];    
                    

To access an element in a C++ array we use the square brackets [ ], just like with Python lists


                    // set the first element in the array to the value 13
                    //   (it must be an integer array or this will not compile)
                    values[0] = 13;

                    int first = values[0];
                    

Array Literals

To create a literal, or value, of type integer array we use the braces { }

Here is code to create a variable of type array of integers and initialize it with specified values:


                    int values[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
                    

Note that we don't need to provide the size if we assign the variable to a value of type integer array.

C-strings

The C-string type is just an array of characters, or char type.


                    // note you don't need a size for this array either
                    char name[] = "Edsger Dijkstra";  
                    

const Keyword

Once created, an array's size cannot change. Also, the size of the array is not stored! 😱

  • Best practice is to create an integer variable that stores the size of an array to be used later
    
                        int SIZE_OF_VALUES = 10;
                        int values[SIZE_OF_VALUES];
                        

The above code has a problem if the variable SIZE_OF_VALUES is ever assigned a new value C++ has the const keyword to say that a variable must be constant (i.e., its value is never allowed to change).

Now we have the following code:


                    const int SIZE_OF_VALUES = 10;
                    int values[SIZE_OF_VALUES];
                    

Array: Warning!

Upon creation of a C++ array variable, all the elements contain ⚠️ garbage values ⚠️ unless you assign each individual value or the variable to an array of values.


                    const int SIZE_OF_VALUES = 10;
                    int values[SIZE_OF_VALUES];

                    // we have no idea what values[0] will contain, 
                    //   except that it will be an integer
                    int value = values[0];
                    

Functions

There is no special keyword like def in C++ functions.

Function definitions follow this EBNF pattern:

  TYPE identifier "(" [TYPE identifier ["," TYPE identifier]*] ")" "{" statements "}"

For example,


                    int add(int a, int b) {
                        return a + b;
                    }
                    

Note the braces are needed { } since C++ doesn't care about whitespace — but you should still use good indentation!

Function Support

C++ originally did not have good support for Higher-order functions and had no lambda functions 😭

Higher-order functions and lambdas were introduced in C++11 (the 2011 version) and have continued to improve in C++14 and more recent versions. They are still more rarely used (many C++ courses don't cover them).

  • Java, C# and other languages derived from C++ also now support HOFs and lambdas

Main

C++ code always starts with a special function called main, which always returns an int. Standard practice is to return 0 if the code worked, a negative number on failure.

main takes arguments from command line so it has parameters int argc, char* args[] — first parameter is the number of C-strings in the second parameter, which is an array of C-strings, or main can have no parameters.


                    int main(int argc, char* args[]) { ... }
                    int main() { ... }
                    

Convention is to create a main.cpp file for the main function:


                    #include <cstdio>  // for 'printf' -- or use #include <iostream>

                    int main() {
                        printf("Hello, World!");
                        return 0;
                    }
                    

Example

Here are equivalent programs in Python and C++.

                    def interest(rate, years):
                        return 1 + rate * years

                    print(interest(0.002, 5))
                    

                    #include <cstdio>

                    double interest(double rate, int years) {
                        return 1 + rate * years;
                    }

                    int main() {
                        printf(interest(0.002, 5));
                        return 0;
                    }