M
Miles
Hello all,
When I subclass std::exception and throw an instance of the subclass,
when I call the what() method of the caught exception, it does not
call the overridden method. I'm under the impression that
std::exception declares what() as a virtual method, so I'm at a loss
as to why the subclass's what() is not being called. For example, for
this program:
#include <exception>
#include <iostream>
#include <stdexcept>
class Exception1 : public std::exception {
public:
Exception1() {}
virtual ~Exception1() throw() {}
virtual const char *what() { return "* Exception1 what"; }
};
class Exception2 : public Exception1 {
public:
Exception2() {}
virtual ~Exception2() throw() {}
virtual const char *what() { return "* Exception2 what"; }
};
int main() {
try {
throw Exception2();
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}
try {
throw Exception2();
} catch (Exception1 &e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
I get the output:
10Exception2
* Exception2 what
I expect to see
* Exception2 what
* Exception2 what
I'm seeing this on gcc v4 on two different platforms, so it seems
intentional. Could anyone explain this to me, and what I need to do
to get the expected behavior (besides just using my own base class)?
Thanks,
Miles
When I subclass std::exception and throw an instance of the subclass,
when I call the what() method of the caught exception, it does not
call the overridden method. I'm under the impression that
std::exception declares what() as a virtual method, so I'm at a loss
as to why the subclass's what() is not being called. For example, for
this program:
#include <exception>
#include <iostream>
#include <stdexcept>
class Exception1 : public std::exception {
public:
Exception1() {}
virtual ~Exception1() throw() {}
virtual const char *what() { return "* Exception1 what"; }
};
class Exception2 : public Exception1 {
public:
Exception2() {}
virtual ~Exception2() throw() {}
virtual const char *what() { return "* Exception2 what"; }
};
int main() {
try {
throw Exception2();
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}
try {
throw Exception2();
} catch (Exception1 &e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
I get the output:
10Exception2
* Exception2 what
I expect to see
* Exception2 what
* Exception2 what
I'm seeing this on gcc v4 on two different platforms, so it seems
intentional. Could anyone explain this to me, and what I need to do
to get the expected behavior (besides just using my own base class)?
Thanks,
Miles