Hi, I am writing this template Array class. I am trying out some different functions, anything I can think of to implement. I have written an Add function as follows:
/**Add function - adds an element at the top of the stack**/
//creates new Array 1 larger
//sets position of element(p_item) to top of the array "stack"
void Add(DataType p_item)
{
int m_newSize = m_size+1;
DataType* tempArr = new DataType[m_newSize];
for(int i=0;i<m_size;i++)
tempArr[i] = m_array[i];
tempArr[m_size] = p_item;
m_size = m_newSize;
if(m_array!=0)
delete[] m_array;
m_array = tempArr;
tempArr = 0;
}
Now this works as i expected. The question lies with what I thought of when trying to think of more efficient ways. Here it is:
void Add(DataType p_item)
{
if(m_array!=0)
{
m_size += 1;
m_array[m_size-1] = p_item;
}
}
Ok, obviously this function cares less about memory allocation than my old aunt josie, but why does it work once?
This is my main function:
int main()
{
Array<int> a(5);
a[0] = 0;
a[1] = 1;
a[2] = 2;
a[3] = 3;
a[4] = 4;
a.Add(12);//if I only call this function 1 time ,it works. Why is this?
std::cout<<"A is now "<<a.Size()<<std::endl;
/* a.Add(8);
std::cout<<"A is now "<<a.Size()<<std::endl;*/
return 0;
}
If I just call the 'bad' Add method once, it works fine. Why? What exactly would be going wrong?