What is the type of the exception object in the following thrown:
Question1> range_error r("error"); throw r;
Answer1> an object of range_error
Question2> exception *p = &r; throw *p;
Answer2> a sliced object of exception
Question3> exception *p = &r; throw p;
Answer3> a pointer pointing to range_error is thrown. The capture-handling can access the range_error member functions through dynamic binding.
Do I get these question right?
// Updated and Compiled and Run on VS2010
#include <iostream>
using namespace std;
class ExClassA
{
public:
virtual void PrintMe() const
{
cout << "ExClassA" << endl;
}
};
class ExClassB : public ExClassA
{
public:
virtual void PrintMe() const
{
cout << "ExClassB" << endl;
}
};
int main(int argc, char* argv[])
{
ExClassB exClassB;
ExClassA *p = &exClassB;
try
{
throw *p;
}
catch (const ExClassA& e)
{
e.PrintMe();
}
try
{
throw p;
}
catch (const ExClassA* e)
{
e->PrintMe();
}
}
The first try-catch of above program prints “ExClassA”
The second try-catch of above program prints “ExClassB”
I think you are right in all three. The type of the thrown object (IIRC) is the static type of the object being thrown. I would have to dig into the standard for a while to find the exact quotes, but a simple example seems to confirm this:
If the dynamic type of the object being thrown was used, then
*bwould have typederivedand the firstcatchwould succeed, but empirically the secondcatchis executed (g++).In the last case, the object thrown is a pointer to
exceptionthat refers to arange_errorobject. The slight difference is again what can be caught, the compiler will not catch in acatch (range_error*)block. The answer is correct, but I would have specified the type of the pointer, as much as the type of the pointee. (The type of the pointer is somehow implicit in the answer)