Why the inheritance from std::exception class gives the different output for the following code snippets:
#include <iostream>
#include <typeinfo>
class Base {};
class Derived: public Base {};
int main()
{
try
{
throw Derived();
}
catch (const Base& ex)
{
std::cout << typeid(ex).name() << '\n';
}
}
Output
class Base
#include <exception>
#include <iostream>
#include <typeinfo>
class Base : public std::exception {};
class Derived: public Base {};
int main()
{
try
{
throw Derived();
}
catch (const Base& ex)
{
std::cout << typeid(ex).name() << '\n';
}
}
Output
class Derived
We call a class polymorphic if it declares or inherits at least one virtual function.
typeid()
behaves differently for polymorphic and non-polymorphic classes: https://stackoverflow.com/a/11484105/367273
Inheriting from std::exception
makes your classes polymorphic (since std::exception
has a virtual destructor and a virtual member function).
This explains the difference in behaviour between the two tests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With