std::bad_cast

Defined in header <typeinfo>
1
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.

std-bad cast-inheritance.svg

Inheritance diagram.

Member functions

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)
[virtual]
returns an explanatory string
(virtual public member function of std::exception)

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#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:

1
Bad dynamic cast
doc_CPP
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.