Why is the unimplemented exception not working?

My example code:

#include<iostream>
using namespace std;

class Parent{ 
        public: 
            virtual void who()
            {
                cout<<"I am parent"<<endl;
            }
};
class Child: public Parent 
{
    public: 
        void who()
        {
            cout<<"I am child"<<endl;
        }
};

int main()
{
    try{
        try{
            Child C;
            Parent &P=C;
            throw P;
        }
        catch(Parent &P)
        {
            P.who();
            throw;//here it just propagates the Child exception
        }
    }
    catch(Parent &P)
    {
            P.who();//parent who is getting executed
    }

}

      

I passed through Scott Mayer. More efficient C ++ clause 12. So when I reverse engineer it, it should propagate the Child exception. But the outer catch

P.who()

gives the parent who()

. And when I change the outer catch to Child

(not mentioned in the program) it ends the process. Where is my understanding wrong?

What Scott Meyers says (with my modifications)

class Widget{...};
class Special Widget: public Widget { ... };
void passAndThrowWidget()
{
   SpecialWidget localSpecialWidget;
   ...
   Widget& rw = localSpecialWidget;
   throw rw; //this throws an exception of type Widget!
} 

................
................

catch(Widget &w)   //catch Widget exceptions
{
  ...
  throw;     //rethrow the exception so it continues to propagate.
}
.............
.............

      

If the original exception was of type Special Widget

, the block catch

will propagate the exception Special Widget

even though the static type w

is Widget. This is because no copy is created after the exception is thrown.

+3


source to share


1 answer


throw rw; //this throws an exception of type Widget!

      

It doesn't throw SpecialWidget

. It only gives out Widget

.



throw;

never changes the type of the thrown object. If the original object was Child

, it will still be a descendant after throw;

.

+3


source







All Articles