std::bad_cast

From Cppreference

Jump to: navigation, search
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).

Contents

[edit] Member functions

(constructor)
constructs a new bad_cast object
(public member function)
operator=
copies a bad_cast object
(public member function)
what [virtual]
returns explanatory string
(virtual public member function)

Inherited from std::exception

Member functions

(destructor) [virtual]
destructs the exception object
(virtual public member function)
what [virtual]
returns explanatory string
(virtual public member function)

[edit] Example

#include <iostream>
#include <typeinfo>
struct Foo {virtual void f() {} };
struct Bar {virtual void f() {} };
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!