Original Post
This post stems from a short discussion I was having about a templated array class that I was writing and was having problems with. The original post is here. Once it was working, I than became interested in various ways of improving it and this is the reason for starting this post. Here's the code for the array class as it is now: Any suggestions on improving/expanding this class would be most welcome. Thanks. ~Casey~ [Edited by - caseyd on March 25, 2006 5:48:00 PM]
template <class DataType>
class Array {
public:
/*
=================
Constructor
Creates an array of p_size.
=================
*/
explicit Array( int p_size )
{
// Create an array of DataType with given size.
m_array = new DataType[p_size];
m_size = p_size;
}
/*
=================
Destructor
Deletes the array
=================
*/
~Array()
{
delete[] m_array;
}
/*
=================
resize
Resizes the current array to p_size.
=================
*/
void resize( int p_size )
{
// Create a temporary array
DataType * tempArray = new DataType[p_size];
// Check to make sure that the temp array
// was initialized okay.
if ( newArray != 0 ) {
// Determine if the new size of the array
// is larger or smaller than the old size.
// If it is smaller, all data in the old array
// past that point will be lost. If it is larger
// we can only copy over the data that was
// in the original array.
int min = p_size < m_size ? p_size : m_size;
int index;
// Copy the contents of the old array into
// the temp array.
for ( index = 0; index < min; index++ ) {
newArray[index] = m_array[index];
}
// Update the size of the new array.
m_size = p_size;
// Delete the old array.
if ( m_array != 0 ) {
delete[] m_array;
}
// Set the old array to the new array
// and we are done.
m_array = newArray;
}
}
/*
=================
operator[]
Returns a reference to DataType
=================
*/
DataType& operator[](int p_index)
{
return m_array[p_index];
}
/*
=================
(conversion) operator *
Returns a pointer to the array.
=================
*/
operator DataType* ()
{
return m_array;
}
private:
DataType * m_array;
int m_size;
};