+ 3

Hey friends please explain me this code and say how <vector> works ?And why output is 6?below

#include <iostream> #include <vector> using namespace std; class A{ public : static int cnt; A(int a){} ~A(){ ++cnt;} }; int A::cnt =0; int main() { vector <A> v(4,1); v.push_back(1); cout<<A::cnt<<endl; return 0; } //output is 6;

14th Sep 2018, 7:07 AM
Albert Whittaker :Shaken To Code
Albert Whittaker :Shaken To Code - avatar
3 odpowiedzi
+ 3
KrOW Nice explanation
14th Sep 2018, 4:46 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 2
Albert Whittaker :Fan Of😍 Motu Patlu😍 This is the logic: 1) at "v" construction a temporary "A" object will be created from casting second param (1) in an "A" object... Because its a temporary object, destructor will be called and "cnt" incremented (after this line, "cnt" is 1) 2) On push_back call, you have "v" with 4 items and because you have not setted an larger capacity, it will resize if grow. This mean that if "v" grows, all items going copied in a a new "space" and old item deallocated. Then, on push_back two things happens: first is created a temporary "A" object (destroyed at end of statement), second push_back copy/allocate and destroy old 4 items. Because of this "cnt" will be incremented 4 (deallocation old items) + 1 (temporary object deallocation) = 5 times and added to previous "cnt" value (1) it will be 6 I hope that i been clear.. If not please ask
14th Sep 2018, 11:35 AM
KrOW
KrOW - avatar
+ 1
Ketan Lalcheta Thank you 😊😊😊
14th Sep 2018, 5:06 PM
KrOW
KrOW - avatar