C++ Type_info Library - bad_cast


Advertisements


Description

It throws an exception on failure to dynamic cast.

Declaration

Following is the declaration for std::bad_cast.

C++98

	
class bad_cast;

C++11

class bad_cast;

Parameters

none

Return Value

none

Exceptions

No-throw guarantee − this member function never throws exceptions.

Data races

The locale object is modified.

Example

In below example for std::bad_cast.

#include <iostream>
#include <typeinfo>
 
struct Foo { virtual ~Foo() {} };
struct Bar { virtual ~Bar() {} };
 
int main() {
   Bar b;
   try {
      Foo& f = dynamic_cast<Foo&&gt;(b);
   } catch(const std::bad_cast& e) {
      std::cout << e.what() << '\n';
   }
}

The output should be like this −

std::bad_cast

typeinfo.htm

Advertisements