Topic: Template classes - Inheritance.


Author: srd320@sparkle.usask.ca (Satya R Dash)
Date: 31 Dec 1994 02:31:01 GMT
Raw View
Hi, I have problem in dynamic memory allocation.

First I have a template "Array" class which takes an constructor with
array size as parameter.  This works fine (possibly because there are
several examples in textbooks).

Now I want to get a derived template class "Matrix" based on "Array"
class. I use the following :

 template <class Type>
 class Matrix : public Array<Type> { . . . }

The problem I am facing is in dynamically building a matrix of some
arbitrary size through a constructor. I am trying to use the overloaded
"new" operator in the following fashion to allocate memory within "Matrix"
class :

  Array<Type> * allocMem( )
    {
      Array<Type> *vectorHd = new Array<Type> [sizeof(Array<Type>)*rows];
      assert ( vectorHd != 0 );
      for( int i=0; i < rows; i++ )
 {
   int offset = sizeof( Array<Type> );
   new ( vectorHd + offset*i ) Array<Type>( columns );
   return vectorHd;
 }
    }

Note :  Variable "columns" is the argument passed  to the "Matrix"
 constructor.

My problem :  The resulting matrix built has a column size as per the
---------- default column size available within the base "Array" class
  and not the argument I pass to the constructor variable
  "columns".

--
Thanks.     Satya Dash





Author: fjh@munta.cs.mu.OZ.AU (Fergus Henderson)
Date: Sat, 31 Dec 1994 18:53:13 GMT
Raw View
srd320@sparkle.usask.ca (Satya R Dash) writes:

>The problem I am facing is in dynamically building a matrix of some
>arbitrary size through a constructor. I am trying to use the overloaded
>"new" operator in the following fashion to allocate memory within "Matrix"
>class :
>
>  Array<Type> * allocMem( )
>    {
>      Array<Type> *vectorHd = new Array<Type> [sizeof(Array<Type>)*rows];

Change that line to

       Array<Type> *vectorHd =
  (Array<Type>*) new char [sizeof(Array<Type>)*rows];

or (preferably)

       Array<Type> *vectorHd =
  (Array<Type>*) operator new (sizeof(Array<Type>)*rows);

You'll also need to make sure that you delete it in the appropriate manner.

>      for( int i=0; i < rows; i++ )
> {
>   int offset = sizeof( Array<Type> );
>   new ( vectorHd + offset*i ) Array<Type>( columns );

Change those two lines to

 new ( &vectorHd[i] ) Array<Type>( columns );

>   return vectorHd;
> }
>    }
>
>Note :  Variable "columns" is the argument passed  to the "Matrix"
> constructor.
>
>My problem :  The resulting matrix built has a column size as per the
>---------- default column size available within the base "Array" class
>  and not the argument I pass to the constructor variable
>  "columns".

You should probably pass `columns' as an argument to allocMem().

--
Fergus Henderson - fjh@munta.cs.mu.oz.au