0

First of all I'm sorry for the title, couldn't explain it clearly using only one sentence..

I'm creating an object that has an array and a counter to count how many elements are inside the array at any time, but somehow, the counter loses its value everytime I'm adding a number. I'm using the following function in order to add elements into the array:

    Heap operator+=(int newHeap)
    {
this->arr[arr_counter] = newHeap;
cout<<newHeap<<" was added to the Heap"<<endl;
cout <<"Currect counter is:"<<arr_counter<<endl;
this->arr_counter++;
cout <<"Currect counter is:"<<arr_counter<<endl;
 }

As you can see, after adding an element into the array, I'm increasing the counter by 1.

The code that I'm running in the main is:

Heap<int> hi(10);
int curr;
((hi += 3) += 2);

But somehow, I'm getting the following output:

10 was added to the integers heap!
3 was added to the Heap
Currect counter is:1
Currect counter is:2
2 was added to the Heap
Currect counter is:-2
Currect counter is:-1

Is there any reason, whatsoever, for the counter to turn into -2 on the next time I'm using the function?

If it helps, the rest of the class is defined that way:

template <>
class Heap<int> {
public:
    Heap (int x) {
arr[0]=x;
arr_counter=1;
    cout<<this->arr[0]<< " was added to the integers heap!"<<endl;
    }
//...some other functions
private:
    int arr[10];
int arr_counter;
    };
Voxito
  • 33
  • 8
  • 3
    You have UB in your code. There's no return statement in your implementation of `Heap operator+=(int newHeap)`,. Again, you probably meant `Heap& operator+=(int newHeap)` – WhiZTiM Feb 21 '17 at 08:55

1 Answers1

2

Heap operator+=(int newHeap) should be Heap& operator+=(int newHeap) and needs to return *this in order to work. I don't think the code as-is compiles. It's a good habit to turn on higher level of compiler warnings.

Based on the incomplete code you posted, it can either be an uninitialized variable issue, or object memory corruption (Do you memset 0 anywhere?)

TheWisp
  • 306
  • 1
  • 6
  • I have initialized the counter in the contructor itself, but I still don't know why it suddenly decided to turn the value of the counter to -2. Anyway, what you wrote helped me solved the problem for now, thanks :) – Voxito Feb 21 '17 at 09:09