Class Templates
collections of objects. These are the data structures studied in CMSC 341.
SmartArray re-revisited
The SmartArray class we designed earlier in the semester
contain a dynamically allocated array of integers. We could specify
the maximum size as a parameter, rather than in the constructor.
template
class SmartArray
{
public:
SmartArray ( void );
// other members
private:
int m_size;
T *m_theData; // array of any type
};
Each of the SmartArray methods is a function template
// SmartArray constructor
template
SmartArray::SmartArray ( void )
{
m_size = size;
m_theData = new T [m_size]; // an array of Ts using T's default constructor
}
//-----------------------------------
// copy constructor
//-----------------------------------
template
SmartArray::SmartArray (const SmartArray& array)
{
m_size = array.m_size;
m_theData = new T [ m_size ];
for (int j = 0; j < m_size; j++ )
m_theData[ j ] = array.m_theData [ j ];
}
Using the SmartArray class template
In the main program,
#include "SmartArray.H"
Define some SmartArrays:
SmartArray array1;
SmartArray array2;