bad_cast Exception

catch (bad_cast)
   statement

The bad_cast exception is thrown by the dynamic_cast operator as the result of a failed cast to a reference type.

The interface for bad_cast is:

class _CRTIMP bad_cast : public exception {
public:
    bad_cast(const __exString& what_arg) : exception (what_arg) {}
};

The following code contains an example of a failed dynamic_cast that throws the bad_cast exception.

//compile with cl /GX /GR
#include <typeinfo.h>
#include <iostream.h>

class Shape {
public:
  virtual void virtualfunc() const {}
};

class Circle: public Shape {
public:
  virtual void virtualfunc() const
  {
  };
};

void main() {
  Shape shape_instance;
  Shape& ref_shape = shape_instance;
  try {
    Circle& ref_circle = dynamic_cast<Circle&>(ref_shape);
  }
  catch (bad_cast) {
    cout << "Caught: bad_cast exception. A Shape is not a Circle.\n";
  }
}

The exception is thrown because the object being cast (a Shape) is not derived from the specified cast type (Circle). To avoid the exception, add these declarations:

  Circle circle_instance;
  Circle& ref_circle = circle_instance;

Then comment out the offending line and reverse the sense of the cast as follows:

  Shape& ref_shape = dynamic_cast<Shape&>(ref_circle);