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;
}
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With