Introductory C++ Notes

C++ is a general-purpose programming language originally designed by Bjarne Stroustrup. He began the project in 1979 and called it “C with Classes”. Like C, aimed to make it a good language for systems programming.

Almost all features of C exist in C++, but in many cases C++ provides better alternatives. Some of the major differences between C and C++ are:

  • C++ has classes and methods, which supports object orient programming (OOP).
  • C++ has generics, which can pass types as parameters to functions. In contrast, C only lets you pass values to functions.
  • C++ has exceptions, which is a general-purpose way of generating and handling error conditions.
  • C++ has support for functional programming, a style of programming where functions are passed as parameters and returned as values.
  • C++ has many smaller improvements and features that aim to make programming easier and less error-prone without sacrificing efficiency.

The sample code that follows is available in this repository.

Introduction to Some C++ Features

The follow sequence of programs shows some features of C++ in action. Please read through them all:

  • intro1.cpp: Shows how to count words in a file. Introduces basic C++ syntax, including namespaces, the string class, and ifstream.
  • intro2.cpp: Like intro1.cpp, but adds a vector and reads files as a vector<string> of words. Shows the use of push_back and size on a vector.
  • intro3.cpp: Shows how to read a file line-by-line using getline.
  • intro4.cpp: Based on intro3.cpp, includes functions read_line and read_string for reading a text files as a vector<string> and string respectively. read_string includes examples of how to use auto and for-each loops in C++.
  • intro5.cpp: Shows how to call the sort function on a vector<string>.

Pass by Reference

In C, all parameters are passed by value, i.e. a copy of the value being passed is given to the function. C++ adds the possibility of passing by reference, which passes the actual value to the function without making a copy. Pass by reference can not only be more efficient, but it allows functions to modify the passed-in values in ways that pass by value cannot do.

swap1.cpp introduces the idea of passing by reference using swap functions.

Using Some Standard Algorithms

C++ has large collection standard library functions, including a set of algorithms called the Standard Template Library, or STL for short.

  • stats1.cpp: simple statistics on a vector<double>. Uses sort to find the min, max, and median.
  • stats2.cpp: based on stats1.cpp, but implements min/max/median as three separate functions.
  • stats3.cpp: based on stats2.cpp, but uses std::min_element and std::max_element.

Operator and Function Overloading

vector_arith1.cpp demonstrates operator and function overloading, including an example of how to overload the << operator for printing.