ilansch
ilansch

Reputation: 4878

cpp static object instantiation

I am newbie to CPP.
I need to add static member that can be called from a static method.
So in the .h i declare it:

static uint32_t s_MyStaticMember; 

Above my constructor (in the "namespace") I initialize it:

uint32_t MyClassName::s_MyStaticMember;

Now I can use this static member from my static method.
The question is, if I initialize the member with =0;

uint32_t MyClassName::s_MyStaticMember=0;" 

What will happen on the next instantiation of the class ?
I assume it will not reset the static member to 0 because this is the reason the initialize is out of the class, the =0 will happen only once.

Is my assumption correct ?

Upvotes: 0

Views: 211

Answers (2)

user1316208
user1316208

Reputation: 687

Yes. Static member variables are akin to global variables in a namespace. They only have one instance. Their initialization will happen only once before the execution even enters your main().

Upvotes: 3

Useless
Useless

Reputation: 67723

Static variables are only initialized once, in the static initialization phase of program startup (reference: [basic.start.static]). The compiler is responsible for making sure there's only one instance of Counted::count, and that it gets initialized exactly once, before any of your other code runs.

Note that if you don't explicitly initialize a static (so you just define it without the = 0), it is anyway zero-initialized by default.

Constucting instances of your class has no effect on non-instance (ie, static) members at all, unless your constructor explicitly writes to them, eg.

struct Counted {
  static unsigned count;
  Counted() { ++count; }
  ~Counted() { --count; }
};

unsigned Counted::count;

the constructor does alter the static, but it doesn't re-initialize it.

Upvotes: 3

Related Questions