0

I have a static variable in my class , which I instantiate in the cpp file to value 1000.

class Container
{
private: 
    static long GLOBALID;
    long MyID;
public:

    Container();
    long GetId();   
};

The code for cpp file.

long Container::GLOBALID = 1000;

Container::Container()
{
    MyID = GLOBALID++;

}

long Container::GetId()
{
    return MyID;
}

When I print the ID value of container objects, they keep incrementing.

My question is that when I create a new object I instantiate the static varible to value 0f 1000 so why does it keep incrementing with each object created?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Summit
  • 2,112
  • 2
  • 12
  • 36
  • 5
    because you increment it on each object construction ... – bolov Feb 28 '20 at 07:26
  • @bolov but when i create a new object than i again set it to 1000 in the cpp file – Summit Feb 28 '20 at 07:27
  • 7
    "when i create a new object i instantiate the static varible to value 0f 1000" - static variables can only be instantiated once , which happens on program startup for this one – M.M Feb 28 '20 at 07:27

1 Answers1

4

With each new Container object created, you increment the Container::GLOBALID number by 1. This is due to the fact that you call MyID = GLOBALID++ inside the Container constructor, which returns the GLOBALID and then increments it, see prefix and postfix increments