I found another idiosyncrasy in a small program I a writing. I am writing a Dynamic Array class that looks likes this:
class DynamicArray{
friend ostream& operator<<(ostream&, DynamicArray&);
public:
DynamicArray(const int& capacity=1) : array(new int[capacity]), capacity(capacity), size(0)
{
for(int i = 0; i < capacity; i++)
{
array[i] = NULL;
}
}
int& operator[](const int index){
sizeOfArray();
return array[index];
}
int sizeOfArray(){
for(int i = 0; i < capacity; i++){
if(array[i] != NULL){ size++; }
}
return size;
}
private:
int* array;
int size;
int capacity;
};
The problem occurs in the index operator. I added a call to the sizeOfArray function so that it updates everytime the user uses it. Example:
int main(){
DynamicArray a(2);
a[0] = 1; // <- this should update the size of the array to 1
return 0;
}
This does not work. Instead I get an error resulting in the display going haywire and spitting out garbage code until the console crashes. Now, the curious thing about this is, if I remove the call to the function in the index operator overloading function, and leave the call before the for loop in the ostream overloading function, the output is correct. Does anyone know why?

New Topic/Question
Reply


MultiQuote




|