+ 1

I have a complete error free program output is 3 but problem is that how did output come 3 can you please tell me. ?

#include <iostream> using namespace std; class A { public: static int a; A() {a++;} }; int A::a=1; void f(void){ A a; throw string("?"); } int main() { A a; try {f();} catch (string &s){} cout<<A::a; return 0; }

23rd Sep 2017, 6:43 AM
Anuj kumar
Anuj kumar - avatar
4 ответов
+ 11
#include <iostream> using namespace std; class A { public: static int a; A() {a++;} }; int A::a=1; // a initialized to 1. void f(void){ A a; throw string("?"); } int main() { A a; // constructor of A is called. // Value of a is now 2. try {f();} // constructor of A is called again. // Value of a is now 3. catch (string &s){} cout<<A::a; // prints 3. return 0; }
23rd Sep 2017, 6:58 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
The second constructor is called in f, when you stated 'A a;'
23rd Sep 2017, 7:57 AM
John Wells
John Wells - avatar
+ 1
@hatsy rei thanks but can you please tell me why did constructor call two times ? it is confusing me
23rd Sep 2017, 7:05 AM
Anuj kumar
Anuj kumar - avatar
+ 1
john well thanks
23rd Sep 2017, 10:38 AM
Anuj kumar
Anuj kumar - avatar