Inheritance from std::exception class and typeid

Viewed 605

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

1 Answers
Related