Why is the answer to this question 1? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
10th Nov 2019, 11:51 AM
Sonic
Sonic - avatar
4 Answers
+ 6
You can probably see it a bit more clearly if we mark A(int) as explicit. In which case std::vector<A> v( 5, 1 ); is illegal and becomes std::vector<A> v( 5, A( 1 ) ); ( the copy constructor is called for the rest ) As you can probably see, you're creating a temporary variable. It gets destructed immediately after the call, which results in 'cnt' getting incremented once in the destructor.
10th Nov 2019, 12:33 PM
Dennis
Dennis - avatar
+ 8
Thanks ~ swim ~ . Incrementing A::cnt by 5 at the time of termination of the program due to the destruction of the 5 object elements was obvious to me. It was the creation and destruction of the temporary object that was not obvious to me.
10th Nov 2019, 11:39 PM
Sonic
Sonic - avatar
+ 3
Yep. Imma dumb haha just figured that out hah
10th Nov 2019, 12:46 PM
jay
jay - avatar
+ 1
Because there is a destructor that increments it
12th Nov 2019, 6:05 AM
I Love You (Challenge Me In C++)
I Love You (Challenge Me In C++) - avatar