By Bjarne Stroustrup

https://isocpp.org/tour

Much of today’s existence relies on software. C++ was designed to write quality software and its features are there to improve that quality.

Chapter 2: The basics

C++ is compiled. That means the source files are compiled into object files and the object files are linked into executables. Executables are made for a particular combination of OS (or not) and hardware and are not portable. However, C++ is portable because the source files can be compiled into an executable for many system combinations.

There are two main parts to standardized C++. Core language features are things like keywords and how to declare variables and functions. The other part is Standard-library components which is usually “extra” C++ code that canonizes many commonly used pieces of software like data structures or algorithms.

C++ is statically typed. This means the type of all things is known at compile time. A type specifies the set of operations allowed on an object.


// include declarations defined in iostream
#include <iostream>

// All cpp programs require one global main function.
// Returning zero or nothing indicates a successful program.  Returning a
// non-zero integer indicates something went wrong.
int main() {
    // std is a namespace
    std::cout << "hello" << std::endl;
}

If a function doesn’t return a value, you can use void to specify that the function doesn’t return anything.

Types

A declaration introduces a new name into a program: <type> <name>.

  • A type defines a set of possible values and a set of operations (for an object).
  • An object is some memory that holds a value of some type.
  • A value is a set of bits interpreted according to a type.
  • A variable is a named object.

C++ has a few fundamental types: bool, char, int, double. The size of each can change between implementations of the compiler, but char and bool are usually 1 byte in size. Other types are usually multiples of char. You can find the size of a type using typeof(<type>).

Below are common operations. For arithmetic operations and assignments, C++ will do implicit type conversion:

x+y // plus
+x // unary plus
xy // minus
x // unary minus
xy // multiply
x/y // divide
x%y // remainder (modulus) for integers

x==y // equal
x!=y // not equal
x<y // less than
x>y // greater than
x<=y // less than or equal
x>=y // greater than or equal

There are a few ways to initialize variables:

double d1 = 2.3;
double d2{2.3};
complex<double> z = 1; // a complex number with double-precision floating-point scalars
complex<double> z2{d1,d2};
complex<double> z3 = {1,2}; // the = is optional with { ... }
vector<int> v{1,2,3,4,5,6}; // a vector of ints

The book recommends using the bracket notation because it saves you from implicit narrowing conversions (both of these may generate an error in modern C++ standards):

int a = 3.1;
int a{3.1}; // Can be better.  Generates an error.