5

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

FrozenHeart
  • 19,844
  • 33
  • 126
  • 242
  • 1
    You can add a virtual function to the `Base` class without inheritance from `std::exception` to make the code snippets behave identically. – Dmitry Markin Dec 27 '13 at 12:15

1 Answers1

6

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.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012