Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try except and inheritance

Why the result is "B", I thought that it should hit first inherited class ("A")? When I ran it with class B that do not inherit anything from class A it hits first catch block, but I don't know reason for behavior like this in code below:

#include <iostream>
#include <exception>

using namespace std;

class A {};

class B : public A{};

class C : public A, public B {};

int main() {
    try {
        throw C();
    }
    catch (A a) {
        cout << "A" << endl;
    }
    catch (B b) {
        cout << "B" << endl;
    }
    catch (C c) {
        cout << "C" << endl;
    }
}   
like image 624
Nikola Nikolic Avatar asked Aug 09 '26 11:08

Nikola Nikolic


1 Answers

For getting the behaviour you expect you should derive virtually.
And also a hint as a guideline throw by value - catch by reference

#include <iostream>
#include <exception>

class A {};

class B : virtual public A {};

class C : public virtual  A, public B {};

int main() {
    try {
        throw C();
    }
    catch (A const& a) {
        std::cout << "A" << std::endl;
    }
    catch (B const& b) {
        std::cout << "B" << std::endl;
    }
    catch (C const& c) {
        std::cout << "C" << std::endl;
    }
}
like image 75
Eduard Rostomyan Avatar answered Aug 12 '26 03:08

Eduard Rostomyan