O'Reilly logo

Essential C++ by Stanley B. Lippman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required