+ 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; }
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;
}
+ 5
The second constructor is called in f, when you stated 'A a;'
+ 1
@hatsy rei thanks
but can you please tell me why did constructor call two times ? it is confusing me
+ 1
john well thanks