std::bad_cast

From cppreference.com
< cpplrm; | types
Type support
Basic types
Fundamental types
Fixed width integer types (C++11)
Numeric limits
C numeric limits interface
Runtime type information
bad_cast
Type traits
Type categories
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
Type properties
(C++11)
(C++11)
(C++14)
(C++11)
(C++11)(until C++20)
(C++11)(deprecated in C++20)
(C++11)
Type trait constants
Metafunctions
(C++17)
Endian
(C++20)
Supported operations
Relationships and property queries
(C++11)
(C++11)
Type modifications
(C++11)(C++11)(C++11)
Type transformations
(C++11)
(C++11)
(C++17)
(C++11)(until C++20)(C++17)
std::bad_cast
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), and also from std::use_facet if the requested facet does not exist in the locale.

cpp/error/exceptionstd-bad cast-inheritance.svg

Inheritance diagram

Member functions

constructs a new bad_cast object
(public member function)

Inherited from std::exception

Member functions

[virtual]
destroys the exception object
(virtual public member function of std::exception)
[virtual]
returns an explanatory string
(virtual public member function of std::exception)

Example

#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';
    }
}

Possible output:

Bad dynamic cast