When I write my try/catch blocks I always throw objects by value and catch by reference. I also apply the rule that the most derived classes must come first.
Today I tried to catch BY VALUE violating this main rule. The code below executes without any problem and prints "A4".
Question: what type of CCA argument is passed to the exception handler that executes? The original object thrown is CCB passed by value to a CCA object: is this an example of memory slicing problem or somekind of corruption i.e. the object CCA cannot be totally trusted?
Regards
AFG
class CCA{
int m_value;
public:
CCA( int value ) : m_value( value ){}
};
class CCB : public CCA{
public:
CCB( int value ): CCA( value ){}
};
main(){
try{
throw CCB(4);
}catch( CCA a ){
std::cout << " A:" << a.value() << std::endl;
// this is the catch clause that executes
}catch( CCB b ){
std::cout << " B:" << b.value() << std::endl;
}
}
This is slicing: The inability of the base copy constructor to discriminate an argument of the genuinely same type from one of a derived class type: