I have a silly question. I read this article about std::exception http://www.cplusplus.com/doc/tutorial/exceptions/
On catch (exception& e)
, it says:
The reason for using &
with exceptions is not so much polymorphism as avoiding slicing. If you were to not use &
, C++ would attempt to copy the thrown exception into a newly created std::exception
, potentially losing information in the process. Example:
#include
#include
class my_exception : public std::exception {
virtual const char *what() const throw() {
return "Hello, world!";
}
};
int main() {
try {
throw my_exception();
} catch (std::exception e) {
std::cout << e.what() << std::endl;
}
return 0;
}
This will print the default message for std::exception
(in my case, St9exception
) rather than Hello, world!
, because the original exception object was lost by slicing. If we change that to an &
:
#include
#include
class my_exception : public std::exception {
virtual const char *what() const throw() {
return "Hello, world!";
}
};
int main() {
try {
throw my_exception();
} catch (std::exception &e) {
std::cout << e.what() << std::endl;
}
return 0;
}
Now we do see Hello, world!
.