Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance from std::exception class and typeid

Tags:

c++

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

like image 615
FrozenHeart Avatar asked Dec 27 '13 11:12

FrozenHeart


1 Answers

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.

like image 190
NPE Avatar answered Sep 23 '22 05:09

NPE