+ 2
Question from C++ challenge [solved]
I posted a question for this in the activity feed. I want to know why this is the output: https://www.sololearn.com/post/352601/?ref=app
3 Antworten
+ 3
In the code as each time you define a new variable of class A the static int count variable gets incremented.
So,for
int A::cnt=x; //------(1)
vector<A>v(y,n);//-------(2)
v.push_back(z);//-------(3)
n can be any number
So,if the initial value is x and the destructor increments the value by 1 each time it is called .So, at 1st statement the initial value is x and it is incremented once to x+1. in 2nd calling it is incremented y times so value becomes x+y+1 and after that at the 3rd statement it is incremented 1 time to x+y+2.
In our case the x=0,y=4.
So, output cnt is 6.
All the above happens because the static variable is same for all the Same class types.
+ 3
To add on what Viroopaksh chekuri has said, you should also keep in mind that the lines vector<A> v(y,n) and v.push_back(z) create temporary A{n} objects which are then moved before being destroyed..This should add some clarity to @Viroopaksh chekuri's explanation just in case you were wondering why destructors are being called and all we have done is create A objects and we have not yet left the main-function scope
0
@Viroopaksh chekuri, thanks for the answer!