Search code examples
c++classconstructorstatic-variables

c++: Static variable defined in constructor


I'm curious about what is really happening "under the hood" here. I'm creating a Class with an ID variable automatically assigned when the constructor is called, depending on how many instances have been created in the past.

Class:

class MyClass{
int ID;
public:
  MyClass(){
    static int id{1}; // Seems to be redefined every time the constructor is called.
    ID = id++;
  }
};

Main:

int main()
{
  MyClass a; // ID = 1
  MyClass b; // ID = 2
  MyClass c; // ID = 3
  return 0;
}

I'm only used to use static member variables that are initialized in the global scope (i.e. MyClass::staticVariable = 1), so this "in-class" initialization confuses me, as what is really happening.

Is the static variable defined only the first time the line is run, and then ignored? Is this the general behaviour for any function AND member function?


Solution

  • For all intents and purposes the behavior is the same as static member variables that are initialized at global scope, which you seem to grasp. The only difference I can see between the two is the scope, the static variable declared in the constructor is only avalilable at constructor scope, whereas a static variable declared as class member is, of course, avalilable at class scope, following the access rules, as all the ohters.