+ 1
Exception in constructor
Hi Please refer code below: Why destructor cout statement is printed? Derived constructor throws exception so derived object is not constructed and hence destructor should not be called. Right? https://sololearn.com/compiler-playground/c7le3N1Qt4k4/?ref=app
3 odpowiedzi
+ 2
you get your expected behavior if you comment out these parts in your Derived class:
public:
//Derived() = default;
Derived(int)// : Derived()
By doing what you did, even though the parameterized constructor throws an error, the default constructor is still called, so Derived is still instantiated, so you see the Derived destructor being called.
you can confirm by changing your code to:
public:
Derived(){cout << "Derived default\n";}
Derived(int) : Derived()
you did not see it because
Derived = default;
did not have a cout.
The question is why did you write it this way? Are there any advantage to doing this?
+ 1
Just a dummy scenario. Not making much sense here , but in case default constructor doing some thing and same is done by parametric one. So, delegating to default constructor and then doing additional stuff where exception occurs.
So, in my thought, derived was not fully constructed and hence no destructor call was expected
0
I learnt that for no reason should a constructor throw an exception without catching it in the same block. The reason, I can't remember but I think undefined behavior is part