Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
Miscellaneous
Miscellaneous
complex
exception
functional
iterator
limits
locale
memory
new
numeric
stdexcept
typeinfo
utility
valarray
typeinfo
bad_cast
bad_typeid
type_info


bad_cast

class
<typeinfo>
class bad_cast;

Exception thrown on failure to dynamic cast

bad_cast

Type of the exceptions thrown by dynamic_cast when they fail the run-time check performed on references to polymorphic class types.

The run-time check fails if the object would be an incomplete object of the destination type.

Its member what returns a null-terminated character sequence identifying the exception.

Some functions in the standard library may also throw this exception to signal a type-casting error.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// bad_cast example
#include <iostream>
#include <typeinfo>
using namespace std;
class Base {virtual void Member(){}};
class Derived : Base {};
int main () {
  try
  {
    Base b;
    Derived& rd = dynamic_cast<Derived&>(b);
  }
  catch (bad_cast& bc)
  {
     cerr << "bad_cast caught: " << bc.what() << endl;
  }
  return 0;
}


Possible output:

bad_cast caught: St8bad_cast

See also