Lecture 5: The Vector class

../_images/L5-title.png Lecture 5 slides Lecture 5 panopto Podcast

(Originally recorded 2019-04-16)

In this lecture we continue exploration of C++ support for classes, looking at constructors and accessors and overloading. And const.

We ultimately arrive at the following Vector class:

#include <vector>

class Vector {
public:
  Vector(size_t M) : num_rows_(M), storage_(num_rows_) {}

        double& operator()(size_t i)       { return storage_[i]; }
  const double& operator()(size_t i) const { return storage_[i]; }

  size_t num_rows() const { return num_rows_; }

private:
  size_t num_rows_;
  std::vector<double> storage_;
};

This is a straightforward, but surprisingly powerful, representation for a vector. No more really needs to be done with the class itself. The operations we are now going to be doing with it simply use the public interface provided by operator().

Note that there are two defintions for operator() – one const and one not.

Important C++ concepts that we focus on during the development are

  • class definition

  • member functions

  • private and public

  • constructors

  • initialization syntax

  • operators

  • operator+

  • operator()

  • const