'How is the static variable in the program below storing new numbers since the definition states that its memory is fixed?

In the online module for my C++ class called zyBooks, static data members are defined as:

The keyword static indicates a variable is allocated in memory only once during a program's execution. Static variables reside in the program's static memory region and have a global scope. Thus, static variables can be accessed from anywhere in a program.

In a class, a static data member is a data member of the class instead of a data member of each class object. Thus, static data members are independent of any class object, and can be accessed without creating a class object.

In the example below,

class Store {
   public:
      Store(string storeName, string storeType);
      int getId();
      static int nextId;   // Declare static member variable  
   private:
      string name = "None";
      string type = "None";
      int id = 0;
};

Store::Store(string storeName, string storeType) {
   name = storeName;
   type = storeType;
   id = nextId;   // Assign object id with nextId
      
   ++nextId;      // Increment nextId for next object to be created
}
...
int Store::nextId = 101; // Define and initialize static data member

int main() {
   
   Store store1("Macy's", "Department");
   Store store2("Albertsons", "Grocery");
   Store store3("Ace", "Hardware");

   cout << "Store 1's ID: "<< store1.getId() << endl;
   cout << "Store 2's ID: "<< store2.getId() << endl;
   cout << "Store 3's ID: "<< store3.getId() << endl;
   cout << "Next ID: " << Store::nextId << endl;

   return 0;   
}
/*
OUTPUT:
Console
Store 1's ID: 101
Store 2's ID: 102
Store 3's ID: 103
Next ID: 104
*/

How does the static member nextId store the increasing numbers for each object created? Is a new, random static region in the memory occupied every time an object is created? Or Is the static data member's memory region expanding to hold more numbers for each object created?



Solution 1:[1]

From cpp reference:

Static data members are not associated with any object. They exist even if no objects of the class have been defined. There is only one instance of the static data member in the entire program with static storage duration, unless the keyword thread_local is used, in which case there is one such object per thread with thread storage duration (since C++11).

The variables declared as static are initialized only once as they are allocated space in separate static storage so, the static variables in a class are shared by the objects. There can not be multiple copies of same static variables for different objects.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 j23