+ 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

4th Nov 2024, 10:44 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Réponses
+ 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?
4th Nov 2024, 11:30 PM
Bob_Li
Bob_Li - avatar
+ 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
5th Nov 2024, 4:32 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
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
5th Nov 2024, 12:07 PM
RuntimeTerror
RuntimeTerror - avatar