Here's a short example:
X3DData_Array2D<int> a(5, 5);
a.Get(2, 2) = 15;
X3DData_Array2D<int> b(a); // error here
cout << b.Get(2, 2) << endl;
When I set break points at each constructor it only hits the copy constructor. Because of that, the first object (b) on the left is still uninitialized with the member variables.
Code:
template <typename T>
class X3DData_Array2D
{
private:
T *m_array;
int m_width;
int m_height;
public:
X3DData_Array2D(int width, int height)
{
m_array = new T[width * height];
m_width = width;
m_height = height;
}
X3DData_Array2D(const X3DData_Array2D &o)
{
int min_width, min_height, t1, t2;
T *newArray;
// Create the new array with the requested size.
newArray = new T[o.m_width * o.m_height];
// Determine minimum size to copy over.
min_width = (o.m_width < m_width) ? o.m_width : m_width;
min_height = (o.m_height < m_height) ? o.m_height : m_height;
// Copy over data.
for (int y = 0; y < min_height; y++)
{
t1 = y * o.m_width;
t2 = y * m_width;
for (int x = 0; x < min_width; x++)
{
newArray[t1 + x] = m_array[t2 + x];
}
}
// Delete the old array.
if (m_array != NULL) {
delete [] m_array;
m_array = NULL;
}
// Store member variables.
m_array = newArray;
m_width = o.m_width;
m_height = o.m_height;
}
~X3DData_Array2D()
{
if (m_array != NULL)
{
delete [] m_array;
m_array = NULL;
}
}