Eliminate Exceptions

Here main():

int main()
{
    B b(1,"two","three");
    try
    {
        f1(b);
    }
    catch(B& b_ref)
    {
        cout<<"Caught B&"<<endl;
        b_ref.print();
    }
    catch(A& a_ref)
    {
        cout<<"Caught A&"<<endl;
        a_ref.print();
    }

    system("pause");
    return 0;
}

Here f1():

void f1(A& subject)
{
    throw subject;
}    

information:

B inherits from A. A::print()is virtual and is redefined to B. A trap that catches the exception, catch(A& a_ref)which, I think, makes sense, since the static type (object) of the exceptions is A &. BUT why doesn't it work B:: print()? Is the dynamic type "lost"? Only a line A::print()is executed in a line a_ref.print();.

Can someone explain?

+3
source share
6 answers

throw . subject A&, , , A ( , , ).

, - , . , , , throw *this.

http://www.ddj.com/cpp/184401940

+6

++ 15.1/3:

- , , cv- ...

, A, B.

+6

"throw subject", throw (subject). , subject , , . A - , subject. (, , ) , .

+5

, . :

void f1(A& subject)
{
    throw subject;
}

you throw A, although the item passed to the function is B.

+4
source

Since you will catch the link, the object is "chopped."

If you really need polymorphic behavior, try using something like the pimpl idiom.

-1
source

nvm, I do not have reading skills. Thought he was creating objects of type A.

-1
source

Source: https://habr.com/ru/post/1714204/


All Articles