In addition to answer 1 and 2, it is important to notice that since
A
constructor increment
x
static member, it is important to be aware that constant expression are initialized before dynamic initialization.
Thus
a
is initialized to
5
first.
Then the initialization of
y
will cause
x
to increment to
6
.
Then in main, objects
a
and
b
will cause
x
to be incremented twice. Thus the value would be 8 after both constructors are called.
Since
x
is static both
cout
statements will output the same variable which will hold
8
at that point. Thus the output will be:
8
8
Finally it is interesting to note that since the copy constructor is not defined, counting would not balance if the copy constructor would have been used.
Also since there is a new used to initialize a static variable there will be no corresponding destructor called at the end of the programm.
When main is exited, destructors for
b
and
a
are called thus
x
will have a value of
6
when the program is about to exit.
In this case it does not matter much but if the counter would have been used for ressources that must be explicitly released (typically out-of-process ressources), then it would have been problematic.