I am quite confused about the type of the object which is rethrown in C++. For example, in the code above, why is the output 241?
My understanding is that in Line 1, an object of class Bar is thrown. It is caught in Line 2. The object of type Bar is sliced to type of Foo.
However, when the exception is rethrown, what's the type of that? Why Line 3 is executed? It's not Foo any more?
What's the basic policy of rethrow? The type remains the same? Or anything changed?
#include <iostream>
using namespace std;
class Foo{
public:
Foo(int i): i(i) {}
Foo(){}
int i;
};
class Bar: public Foo{
public:
Bar(int i): Foo(i) {}
Bar(const Bar& b){i=b.i;}
};
int main () {
Bar b(1);
try{
try{
throw b; //Line 1
}
catch(Foo& e){
e.i=2; //Line 2
cout<<e.i;
throw;
}
catch(Bar& e){
e.i = 3;
cout<<e.i;
throw e;
}
}
catch (Bar e) {
e.i*=2; //Line 3
cout<<e.i;
}
catch (Foo e) {
e.i*=3;
cout<<e.i;
}
cout<<b.i;
return 0;
}