My answer matches the linux compiler and hopefully it should be true for everyone. The catch order depends on two factors:
(1) First choose the first option ; If the base class appears before the derivative, it will be given a choice. Some compilers warn about this, some do not;
(2) Type of inheritance ; Either public or non-public (private / secure)
struct B {}; struct D : B {}; struct DD : D {}; int main() { for(int i = 0; i < 3; i++) { try { switch(i) { case 0: throw new B; case 1: throw new D; case 2: throw new DD; } } catch(B *o) { cout<<"B* caught\n"; } catch(D *o) { cout<<"D* caught\n"; } catch(DD *o) { cout<<"DD* caught\n"; } } }
(1) In the above code, it always catches B., if you change the order with the trap DD, D, B, then it will meet your expectations when preference will be given to Derived classes.
(2) Now replace 'struct' with 'class' or change the inheritance to private / protected; In the above code, regardless of order, catches will match the type of throw. It will be so strict that even if you delete any of the catch of the Derived class, it will not be caught by the base class.
iammilind
source share