Lab #5

Templates and inheritance, composition, a complete class for matrices

Cristiano De Michele

Today

  1. Introduction to C++ (part V) — a class template derived from a class template and the keyword using (example N10), a std::vector of objects (N11), composition and multiple inheritance (N12).
  2. Lab #4: the solution — pvector as a class template, random(L), random_orient(), and the first methods of pmatrixq.
  3. Task: complete pmatrixq — += and -=, products and divisions by a scalar, matrix times vector and vector times matrix, matrix times matrix, transpose and ==.

Part 1
Introduction to C++ (part V)

Where we left off

  • Since Lab #4 pvector and pmatrixq are class templates: pvector<double,3>, pmatrixq<double,3>.
  • In the Monte Carlo and molecular dynamics code we will also need:
    • a class template derived from another class template: a particle with the Lennard-Jones interaction, particleLJ<ntype>, derived from a generic particle<ntype> (example N10);
    • many objects of the same class, one for each particle: a std::vector of objects (example N11);
    • classes that contain objects of other classes: a particle has a position, a velocity and a force, three pvector (example N12).

Example N10: using.cpp

examples/N10_use_of_using/using.cpp

#include<iostream>
template <typename ntype>
class base {
public:
  void funcbase(void)
    {
      std::cout << "hallo ";
    }
  ntype a;
};

template <typename ntype>
class derived: public base<ntype> {
public:
  using bt = base<ntype>; // this is just an alias (from c++11 on, i.e. use at least -std=c++11 to compile)
  using base<ntype>::a, bt::funcbase; // if we remove this we got a compilation error
  void funcder(void)
    {
      funcbase();
      std::cout << "from derived: " << a << "\n";
    }
  derived(ntype x) // constructor
    {
      a = x;
    }
};

int main(void)
{
  derived<double> A(1.1);
  A.funcder();
  return 0;
}

Example N10: how it works

g++ -std=c++17 -Wall -o using using.cpp && ./using     # prints: hallo from derived: 1.1
  • derived<ntype> inherits from base<ntype>, which depends on the template parameter. When the compiler reads the template, base<ntype> is not a class yet: it is created when the template is instantiated (derived<double> creates base<double>), and for some ntype it could be replaced by a specialization, a different definition with other members. So a name written alone, like funcbase or a, is not looked up there.
  • Comment out line 16: error: there are no arguments to 'funcbase' that depend on a template parameter, so a declaration of 'funcbase' must be available (line 19) and error: 'a' was not declared in this scope (lines 20 and 24).
  • Line 16 says that a and funcbase come from the base class. Alternatives: this->a and this->funcbase(), or base<ntype>::a and base<ntype>::funcbase().
  • using bt = base<ntype>; (line 15): an alias; the comma in line 16 needs C++17.
  • With a base class that is not a template (example N2) none of this is needed.

Example N11: vector.cpp

examples/N11_particle_class/vector.cpp

#include<iostream>
#include<vector>
template <typename ntype>
class particle
{
  ntype rx, ry, rz;
public:
  void show(void)
    {
      std::cout << "particle position is (" << rx << "," << ry << "," << rz << ")\n";
    }
  void set_pos(ntype x, ntype y, ntype z)
    {
      rx = x;
      ry = y;
      rz = z;
    }
};
int main(int argc, char **argv)
{
  using pt = particle<double>; // using to define an alias
  std::vector<pt> p; // vector of particles 
  p.resize(2); // two particles
  p[0].set_pos(1,2,3);
  p[1].set_pos(4,5,6);
  p[0].show();
  p[1].show();
  return 0;
}
g++ -std=c++17 -Wall -o vector vector.cpp
./vector
particle position is (1,2,3)
particle position is (4,5,6)
  • std::vector<pt> (<vector>): an array of objects whose size can change at run time; it manages the memory by itself, no new and delete (Lab #3).
  • p.resize(2): two particles, p[0] and p[1]; p.size() gives their number.
  • pt (line 21): an alias.

Example N12: composition.cpp

examples/N12_composition/composition.cpp

#include<iostream>
class Acl
{
  double da;
public:
  Acl() // constructor
    {
      da = 1.0;
    }
  void showA(void)
    {
      std::cout << da << "\n";
    }
};

class Bcl
{
  // same name as in Acl: Derive inherits both, Acl::da and Bcl::da,
  // so D.da would not compile ("request for member 'da' is ambiguous")
  double da;
public:
  Bcl() // constructor
    {
      da = 2.0;
    }
  void showB(void)
    {
      std::cout << da << "\n";
    } 
};
class Compose // COMPOSITION
{
  int c;
public:
  Acl A;
  Bcl B;
};

class Derive: public Acl, public Bcl // DERIVATION
{
  int c;
public:
};


int main(void)
{
  Derive D;
  Compose C;
  D.showA();
  D.showB();
  C.A.showA();
  C.B.showB();
  //C.B.showA();
}

Example N12: how it works

g++ -std=c++17 -Wall -o composition composition.cpp && ./composition    # prints 1 2 1 2
  • Compose has an Acl and a Bcl, its members A and B: this is composition. Derive is an Acl and is a Bcl: this is multiple inheritance, a class derived from two classes.
  • D.showA() and D.showB() are inherited; C.A.showA() and C.B.showB() go through the members. C.B.showA() (line 55) does not compile: B is only a Bcl, error: 'class Bcl' has no member named 'showA'; did you mean 'showB'?
  • Both base classes have a member da: D contains two of them, and D.da gives error: request for member 'da' is ambiguous (besides error: 'double Acl::da' is private within this context). If both classes had a method show(), D.show() would be ambiguous too, and D.Acl::show() would choose. With composition there is no clash: C.A and C.B are two separate objects.
  • A rule of thumb: inheritance for “is a” (a Lennard-Jones particle is a particle), composition for “has a” (a particle has a position, a pvector).

Part 2
Lab #4: the solution

Task 1 and random(L)

project/pvector.hpp

// STRATEGIES TO MAKE CLASS GENERIC
//#define NT 3
// constexpr tells compiler that NT can be calculated at compile time
//constexpr int NT=3;

//typedef float ntype; // as in C
//using ntype=double; // use "using" to define an alias for the keyword "double"

template <typename ntype, int NT>
class pvector
{
  ntype v[NT]; // private member
  // generate a random vector inside a box and assign it to (*this) object
  void random(const ntype& L)
    {
      for (int i=0; i < NT; i++)
        {
          v[i] = (rng.ranf()-0.5)*L; // assign a random value in [-L/2,L/2)
        }
    }
  • Task 1: NT and ntype commented out, template <typename ntype, int NT> before class pvector; in pvector.cpp, pvector<ntype,NT> R, U;.
  • random(L): (rng.ranf()-0.5)*L is uniform in \([-L/2, L/2)\), one number for each component (rng: the generator of randnumgen.hpp).

random_orient()

project/pvector.hpp

  // generate a random vector on unit sphere and assign it to (*this) object
  void random_orient(void)
    {
      ntype rS, S, V1, V2;
      if (NT==3)
        {
          do
            {
              V1 = 2.0*rng.ranf()-1.0;
              V2 = 2.0*rng.ranf()-1.0;
              S = V1*V1+V2*V2;
            }
          while (S >= 1.0);
          rS = sqrt(1.0-S);
          v[0] = 2.0*rS*V1;
          v[1] = 2.0*rS*V2;
          v[2] = 1.0-2.0*S;
        }
      else
        {
          std::cout << "[random_orient] Only 3D vectors are supported\n";
        }
    }
  • do ... while: steps 1 and 2 of Marsaglia’s algorithm (the rejection), then step 3.
  • With (*this) = {2.0*rS*V1, 2.0*rS*V2, 1.0-2.0*S}; and pvector<float,3>: warning: narrowing conversion ... from 'double' to 'float', since 2.0 is a double; v[0] = ... converts silently.

pmatrixq: the constructors (1)

project/pmatrix.hpp

  pmatrixq()
    {
      for (int i=0; i < NT; i++)
        for (int j=0; j < NT; j++)
          m[i][j]=0;
    }

  // to initialize a matrix as follows: pmatrixq<double,2> M={1,2,3,4};
  pmatrixq(std::initializer_list<ntype> list)
    {
      int cc=0;
      for (auto el: list)
        {
          if (cc < NT*NT)
            m[cc/NT][cc%NT] = el;
          cc++;  
        }
      for ( ; cc < NT*NT; cc++) // shorter list: the others are 0
        m[cc/NT][cc%NT] = 0;
    } 
  • {1,2,...}: the element number cc goes to m[cc/NT][cc%NT], only if cc < NT*NT; with a shorter list the other elements are set to 0, as in the constructor of pvector (Lab #2).

pmatrixq: the constructors (2)

project/pmatrix.hpp

  // to initialize a matrix as follows: pmatrixq<double,2> M={{1,2},{3,4}};
  pmatrixq(std::initializer_list<std::initializer_list<ntype>> list)
    {
      for (int i=0; i < NT; i++) // first all 0: missing ones stay 0
        for (int j=0; j < NT; j++)
          m[i][j]=0;
      int i=0, j=0;
      for (auto r: list)
        {
          j=0;
          for (auto c: r)
            {
              if (i < NT && j < NT)
                m[i][j] = c;
              j++;
            }
          i++;
        }
    } 
  • {{...},{...}}: first all the elements to 0, then two nested range-based for, over the rows and over the elements of each row; if (i < NT && j < NT) never writes outside m. So pmatrixq<double,3> M = {{1,2},{3}}; gives {{1,2,0},{3,0,0},{0,0,0}}.

operator(), <<, +, -

project/pmatrix.hpp

  // ============================================================
  // overloading of () operator to get/set (i,j)-th element
  // m(i,j)=2.0;
  // std::cout << m(i, j);
  ntype& operator()(int i, int j)
    {
      return m[i][j];
     }
  
  ntype operator()(int i, int j) const
    {
      return m[i][j];
    }

  // output (std::cout << M) << "\n";
  friend std::ostream& operator<<(std::ostream& os, const pmatrixq& M1)
    {
      int i, j;
      os << "{";
      for (i=0; i < NT; i++)
        {
          os << "{";
          for (j=0; j < NT; j++)
            {
              os << M1(i,j);
              if (j < NT-1)
                os << ",";
            }
          os << "}";
          if (i < NT-1)
            os << ",";
        }
      os << "}";
      return os;
    }
  // addition 
  pmatrixq operator+(const pmatrixq &M2) const
    {
      // MT = M1 + M2
      pmatrixq MT;
      for (auto i=0; i < NT; i++)
        {
          for (auto j=0; j < NT; j++)
            {
              MT(i,j) = (*this)(i,j) + M2(i,j);
            }
        }
      return MT;
    }
  // subtraction
  pmatrixq operator-(const pmatrixq &M2) const
    {
      // MT = M1 - M2
      pmatrixq MT;
      for (auto i=0; i < NT; i++)
        {
          for (auto j=0; j < NT; j++)
            {
              MT(i,j) = (*this)(i,j) - M2(i,j);
            }
        }
      return MT;
    }

Part 3
Task: complete pmatrixq

The task

Download again project_classes.zip (unzip it elsewhere, not over your files):

  • project/pvector.hpp: the class template with random() and random_orient() (Part 2);
  • project/pmatrix.hpp: the methods of Lab #4 (Part 2) and the skeletons of the new ones;
  • project/pmatrix.cpp: the new goal, it must print the output at the end of this part.
// [*] += and -= operators
// [*] matrix times scalar (also *=)
// [*] matrix divided by scalar (also /=) 
// [*] scalar times matrix <--- with friend function
// [*] matrix times vector 
// [*] vector times matrix <--- with friend function
// [*] matrix times matrix (also *=)
// [*] transpose
// [*] operator == to pmatrix class

Compare your Lab #4 methods with the solution, then go on in the new pmatrix.hpp (or copy the skeletons into yours).

The skeletons (1)

project/pmatrix.hpp

  // ============== LAB #5: skeletons, fill the bodies

  // M1 += M2
  pmatrixq& operator+=(const pmatrixq &M2)
    {
    }

  // M1 -= M2
  pmatrixq& operator-=(const pmatrixq &M2)
    {
    }

  // matrix *= scalar
  pmatrixq& operator*=(const ntype& s)
    {
    }

  // matrix /= scalar
  pmatrixq& operator/=(const ntype& s)
    {
    }

  // matrix times scalar: M*s
  pmatrixq operator*(const ntype& s) const
    {
    }

  // matrix divided by scalar: M/s
  pmatrixq operator/(const ntype& s) const
    {
    }

  // scalar times matrix: s*M (friend function, as "scalar times vector")
  friend pmatrixq operator*(const ntype& s, const pmatrixq &M2)
    {
    }

The skeletons (2)

project/pmatrix.hpp

  // matrix times vector: (M*V)(i) = sum over j of M(i,j)*V(j)
  pvector<ntype,NT> operator*(const pvector<ntype,NT> &V2) const
    {
    }

  // vector times matrix: (V*M)(j) = sum over i of V(i)*M(i,j) (friend function)
  friend pvector<ntype,NT> operator*(const pvector<ntype,NT>& V1, const pmatrixq& M2)
    {
    }

  // matrix times matrix: (M1*M2)(i,j) = sum over k of M1(i,k)*M2(k,j)
  pmatrixq operator*(const pmatrixq &M2) const
    {
    }

  // M1 *= M2, i.e. M1 = M1*M2
  pmatrixq& operator*=(const pmatrixq &M2)
    {
    }

  // transpose: MT(i,j) = M(j,i)
  pmatrixq transpose(void) const
    {
    }

  // M1 == M2: true if all the elements are equal
  bool operator==(const pmatrixq &M2) const
    {
    }

Hints: assignments and scalars

  • M1 += M2 changes M1 and returns it by reference, return (*this);, like operator= of pvector. It can reuse +: *this = *this + M2;. The same for -=.
  • *= and /= with a scalar: two nested loops on m[i][j], then return (*this);.
  • M*s and M/s do not change M: const methods with a local MT, returned by value, like + and -.
  • s*M: the left operand is not a pmatrixq, so it cannot be a method. It is a friend function with two arguments, like “scalar times vector” in pvector (Lab #3), and it can reuse M2*s.
  • operator* has five versions, M*s, s*M, M*V, V*M and M1*M2: the compiler chooses the right one from the types of the operands (overloading, Lab #2).

Hints: products, transpose and ==

  • In formulas: \[(MV)_i = \sum_j M_{ij} V_j \qquad (VM)_j = \sum_i V_i M_{ij} \qquad (M_1 M_2)_{ij} = \sum_k (M_1)_{ik} (M_2)_{kj}\] Each sum is a loop, inside the loops over the free indices: set the sum to 0 first.
  • V*M is a friend of pmatrixq, not of pvector: it can read M2.m, but not V1.v. Use V1(i), otherwise error: 'double pvector<double, 3>::v [3]' is private within this context.
  • M1 *= M2: compute the product in a new matrix first, then assign: *this = (*this)*M2; (why: Classic pitfalls).
  • transpose() returns a new matrix, \(M^T_{ij} = M_{ji}\), and does not change M: a const method.
  • ==: return false at the first element that differs, true after the loops.

The goal: pmatrix.cpp

project/pmatrix.cpp

#include "./pmatrix.hpp"
int main(void)
{
  using ntype = double;       // type of the elements
  constexpr int NT = 3;       // size of the matrices
  pmatrixq<ntype,NT> A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 10}};
  pmatrixq<ntype,NT> B = {{2, 0, 1}, {1, 3, 0}, {0, 1, 4}};
  pmatrixq<ntype,NT> C;
  const pmatrixq<ntype,NT> I = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
  pvector<ntype,NT> V = {1, 2, 3};

  std::cout << "A=" << A << "\n";
  std::cout << "B=" << B << "\n";
  std::cout << "A*2=" << A*2.0 << "\n";
  std::cout << "2*A=" << 2.0*A << "\n";
  std::cout << "A/2=" << A/2.0 << "\n";
  C = A;
  C += B;  std::cout << "C=A, C+=B: " << C << "\n";
  C -= B;  std::cout << "C-=B:      " << C << "\n";
  C *= 3.0; std::cout << "C*=3:      " << C << "\n";
  C /= 3.0; std::cout << "C/=3:      " << C << "\n";
  std::cout << "A*V=" << A*V << "\n";
  std::cout << "V*A=" << V*A << "\n";
  std::cout << "A*B=" << A*B << "\n";
  std::cout << "B*A=" << B*A << "\n";          // the product is not commutative
  C = A;
  C *= B;  std::cout << "C=A, C*=B: " << C << "\n";
  std::cout << "transpose(A)=" << A.transpose() << "\n";
  std::cout << "A*I==A: " << (A*I == A) << "  I*A==A: " << (I*A == A)
            << "  A==B: " << (A == B) << "\n";
  std::cout << "(A*B)^T==B^T*A^T: "
            << ((A*B).transpose() == B.transpose()*A.transpose()) << "\n";
  return 0;
}

Compile, run, compare

cd ~/csm/project
g++ -std=c++17 -Wall -o pmatrix pmatrix.cpp
./pmatrix
A={{1,2,3},{4,5,6},{7,8,10}}
B={{2,0,1},{1,3,0},{0,1,4}}
A*2={{2,4,6},{8,10,12},{14,16,20}}
2*A={{2,4,6},{8,10,12},{14,16,20}}
A/2={{0.5,1,1.5},{2,2.5,3},{3.5,4,5}}
C=A, C+=B: {{3,2,4},{5,8,6},{7,9,14}}
C-=B:      {{1,2,3},{4,5,6},{7,8,10}}
C*=3:      {{3,6,9},{12,15,18},{21,24,30}}
C/=3:      {{1,2,3},{4,5,6},{7,8,10}}
A*V=(14,32,53)
V*A=(30,36,45)
A*B={{4,9,13},{13,21,28},{22,34,47}}
B*A={{9,12,16},{13,17,21},{32,37,46}}
C=A, C*=B: {{4,9,13},{13,21,28},{22,34,47}}
transpose(A)={{1,4,7},{2,5,8},{3,6,10}}
A*I==A: 1  I*A==A: 1  A==B: 0
(A*B)^T==B^T*A^T: 1
  • With the skeletons, 13 warnings: no return statement in function returning non-void, one for each method to write. Do not run the program before they are gone: a method that does not return its value gives garbage, or a crash.
  • \(AB \neq BA\): the product of matrices is not commutative.
  • The last two lines check the code with two identities: \(AI = IA = A\) and \((AB)^T = B^T A^T\).

Classic pitfalls

  • A missing const, e.g. on M1*M2: then I*A, with I declared const, gives error: passing 'const pmatrixq<double, 3>' as 'this' argument discards qualifiers.
  • s*M as a method: an operator method has one explicit operand, the other is *this: error: '... operator*(const ntype&, const pmatrixq<ntype, NT>&)' must have either zero or one argument.
  • The product in place: writing m[i][j] while row i is being computed uses the new m[i][0] to compute m[i][1]: C=A; C*=B; gives {{4,9,16},{13,21,37},{22,34,62}} instead of {{4,9,13},{13,21,28},{22,34,47}}.
  • Swapped indices, e.g. M2(j,k) instead of M2(k,j): it compiles and runs, the expected output catches it.
  • == between double: the comparison is exact. (A*0.1)*10.0 == A is false, because 3*0.1*10 gives 3.0000000000000004. Fine for our tests, with integer elements; in general, compare with a tolerance.

Checklist for today