Exercise 6.2

Reimplement the Matrix class of Exercise 5.3 as a template. In addition, extend it to support arbitrary row and column size using heap memory. Allocate the memory in the constructor and deallocate it in the destructor.

The primary work of this exercise is to add general row and column support. We introduce a constructor that takes a row and a column size as arguments. The body of the constructor allocates the necessary memory from the program’s free store:

Matrix( int rows, int columns ) 
      : _rows( rows ), _cols( columns ) 
{ 
    int size = _rows * _cols; 
    _matrix = new elemType[ size ]; 
    for ( int ix = 0; ix < size; ++ix ) 
          _matrix[ ix ] = elemType(); 
} 

elemType is the template parameter. _matrix is now an elemType pointer that addresses ...

Get Essential C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.