##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# std::bad_cast

From cppreference.com
< cpp‎ | types

Defined in header `<typeinfo>` |  |
class bad_cast : public std::exception; |  |

An exception of this type is thrown when a `dynamic_cast` to a reference type fails the run-time check (e.g. because the types are not related by inheritance).

Inheritance diagram

### [edit] Member functions

(constructor) | constructs a new bad_cast object (public member function)

## Inherited from std::exception

### Member functions

(destructor) [virtual] | destructs the exception object (virtual public member function of `std::exception`) [edit]
what [virtual] | returns an explanatory string (virtual public member function of `std::exception`) [edit]

### [edit] Example

Run this code

    #include <iostream>
    #include <typeinfo>

    struct Foo { virtual ~Foo() {} };
    struct Bar { virtual ~Bar() {} };

    int main()
    {
        Bar b;
        try {
            Foo& f = dynamic_cast<Foo&>(b);
        } catch(const std::bad_cast& e)
        {
            std::cout << e.what() << '\n';
        }
    }

Output:

    Bad dynamic_cast!

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/types/bad_cast&oldid=63177"