Copy Constructor Question
Code:
heap::heap(const heap &aHeap)
{
delete [] heapArr;
heapArr =NULL;
cout << heapArr <<endl;
heapArr = new HeapNode[aHeap.maxSize];
if (heapArr != NULL)
{
maxSize = aHeap.maxSize;
curSize = aHeap.curSize;
for (int a = 0; a <= curSize; a++)
{
heapArr[a] = aHeap.heapArr[a];
}
}
else
maxSize = 0;
}
I've been told that I need the red line because
"you may actually be copying over an existing heap. Think of the situation where a function returns a heap - you could potentially assign the return value to an existing heap that has values in it"
and that the solution is the following code:
Code:
if (heapArr != NULL)
{
delete [] heapArr
heapArr = NULL;
}
Now I've tested this(get a fault) and have some questions. If this constructor is not being used to assign the return value of a heap and is used to create a new heap why would the value in heapArr be NULL? It hasn't been initialized to anything let alone NULL. No other constructor has been called to do so, right?