Re: exception and polymorphism problem
On May 16, 1:04 pm, Erik Wikstr=F6m <eri...@student.chalmers.se> wrote:
On 16 Maj, 13:01, josh <xdevel1...@gmail.com> wrote:
Hi I have this code:
class Exception : public exception
{
public:
Exception(string m="exception!") : msg(m) {}
~Exception() throw() {}
const char* what() { return msg.c_str(); }
private:
string msg;
};
int main()
{
try
{
throw Exception();
}
catch(exception e)
{
cout << e.what() << endl;
}
return 0;
}
when I run it I don't have print out my message "exception!" but
St9exception
Because you catch the exception by value, so you copy-construct a new
std::exception from the Exception that was thrown, catch the exception
by reference instead and it will work:
catch (exception& e)
Just a detail, but he's probably not going to be modifying the
object, so:
catch ( exception const& e )
would be more appropriate. (In practice, in the case of
exceptions, I don't think it makes much difference, but using
const systematically when appropriate is a good habit to get
into.)
--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34