Everytime I run a method called Loan &removeFirst () {} my program keeps on crashing. The program crashes whenever I attempt to delete the temporary Loan structure that I created. I can show some background for the container class and the code for my function:
class ListOfLoans {
public:
//default constructor allocate appropriate heap storage
//store elements on heap array declared like this:
//new Loan*[initial_size];
ListOfLoans(int initial_size = 4) {
elements = new Loan*[initial_size];
numberOfElements = 0;
capacity = initial_size;
index = 0;
}
~ListOfLoans(void) {
cout << "Deleting \n";
delete [] elements;
}
// answer the first element from the list but don't remove it
Loan & first() const {
if (capacity == 0) {
cout << "Attempted on empty list. Exitting!" << endl;
exit;
} else {
return *elements[0];
}
}
// answer the first element from the list and remove it from the list
// if the resulting list is more than three quarters empty release some memory
Loan & removeFirst() {
index--;
if (capacity == 0) {
cout << "Attempted on empty list. Exitting!" << endl;
exit;
}
if(size() < capacity/4) { //shrink the container when 1/4 full
cout << "shrinking\n";
Loan **temp = elements;
elements = new Loan*[capacity/2];
for(index = (numberOfElements - 1); index >= 0; index--) {elements[index] = temp[index];}
capacity /= 2;
delete [] temp; // my program crashes at this line, I want to delete the temp structure
}
return first();
}
private:
Loan ** elements;
int numberOfElements; //number of elements in the list
int capacity; //size of the available array memory
mutable int index; //used to help with the iteration
};