Back to questions
JuniorTheoryCommon
What does the program print?
#include <iostream>
struct Error {
virtual int code() const { return 1; }
};
struct NotFound : public Error {
int code() const override { return 404; }
};
int main() {
try { throw NotFound{}; } catch (Error e) { std::cout << e.code() << ' '; }
try { throw NotFound{}; } catch (const Error& e) { std::cout << e.code(); }
}1 404
- Expecting
404 404:catch (Error e)copies only theErrorpart of the thrownNotFound, socode()runs on a plainError. - Expecting
1 1:const Error& erefers to the thrownNotFounditself, and a virtual call through it runsNotFound::code.
- Why does GCC warn about
catch (Error e)when it builds with-Wall? - Why do you throw the exception object itself rather than a pointer to it?