Search code examples
c++arraysdynamic-arraysstatic-variables

When creating dynamic array static member (counter) is increased


Suppose I am writing a catalogue of items, where each item has unique id. This id is determined by automatically increased counter - static variable, that is initialized to zero. I want my catalogue to be a dynamic array. The problem is, if I create an array of size 10, my static counter will increase to 10 even before I create and place any objects in this array. Why is it so and how can I avoid it?

My example code:

#include <stdlib.h>
#include <iostream>
using namespace std;

class Item
{
private:
    int id;
public:
    static int next_id;
    Item();
};

int Item::next_id = 0;

Item::Item()
{
    id = Item::next_id++;
}

int main()
{
    Item* catalogue;
    catalogue = new Item[10];
    cout << Item::next_id << endl;
    system("pause");
    return 0;
}

And the output is:

10

As you can see, I did not create any Item objects, yet next_id is already 10. So if I try to create an Item object, it will have id of 11.


Solution

  • Here catalogue = new Item[10]; the new operator will call the constructor of the Item class 10 times hence Item::next_id = 10