Re: Basic question C++ exception
On Jun 29, 12:44pm, "AnonMail2...@gmail.com" <AnonMail2...@gmail.com>
wrote:
> On Jun 29, 11:34am, Vijay <mt.vi...@gmail.com> wrote:
>
>
>
> > Hi All,
>
> > I am not able to figure out what exactly happening in below code. what
> > is control flow. Can anyone clear my confusion?
>
> > Code:
> > class A
> > {
> > public:
> > A(){cout<<"In Constructor\n";}
> > //// A(const A&){cout<<"In Copy Constructor\n";} // if we uncomment
> > this, we see different //output .
> > ~A(){cout<<"In Destructor\n";}};
>
> > try{
> > cout<<"In Try\n";
> > throw A();
> > }
> > catch(A &a)
> > {
> > cout<<"In Catch\n";}
>
> > output:
> > In Try;
> > In Constructor
> > In Destructor
> > In Catch
> > In Destructor
>
> > Question 1. I don't know why two times destructor has been called. I
> > understand, since i am using reference, so there would not be any new
> > object. then why two times destructor got called.
>
> > Question 2.
>
> > class A
> > {
> > public:
> > A(){cout<<"In Constructor\n";}
> > A(const A&){cout<<"In Copy Constructor\n";}
> > ~A(){cout<<"In Destructor\n";}};
>
> > try{
> > cout<<"In Try\n";
> > throw A();
> > }
> > catch(A a)
> > {
> > cout<<"In Catch\n";}
>
> > output:
> > In Try;
> > In Constructor
> > In Copy Constructor
> > In Catch
> > In Destructor
> > In Destructor
>
> > Why object created by throw A() has not been deleted while exiting try
> > block in above code?
>
> > thanks in advance.
>
> > Regards,
>
> In the first case, there has to be copy since you are getting two
> destructor
> calls. The copy is done using the default copy constructor which
> doesn't
> print any output. Makes sense to me.
>
> I'm not sure why the order of the destructors are different in the
> second
> example. Could it have anything to do with the fact that the code you
> posted for the second example is catching the exception by value? Or
> is the missing '&' a typo?
Thanks for ur reply. there was no typo.. I want to catching the
exception by value.
regards
|