Michel H
Michel H

Reputation: 363

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?

Upvotes: 1

Views: 780

Answers (2)

anastaciu
anastaciu

Reputation: 23822

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.

Upvotes: 2

Pat. ANDRIA
Pat. ANDRIA

Reputation: 2412

id is a static local variable. Using the static keyword on a local variable changes its duration from automatic duration to static duration.

According to cpp ref, the initialization is done the first time control passes through their declaration. On all further calls, the declaration is skipped.

Static local variables and lifetime-of-a-static-variable are some interesting detailed articles.

Upvotes: 1

Related Questions