Open In App

typeinfo::bad_cast in C++ with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

Standard C++ contains several built-in exception classes. typeinfo::bad_cast is one of them. This is an exception thrown on failure to dynamic cast. Below is the syntax for the same:

Header File:

<typeinfo>

Syntax:

class bad_cast;

Note: To make use of std::bad_cast, one should set up the appropriate try and catch blocks.

Return Value: It doesn’t return anything.

Below are the examples to understand the implementation of std::bad_cast in a better way:

Program 1:




// C++ code for std::bad_cast
#include <bits/stdc++.h>
#include <typeinfo>
  
using namespace std;
  
// Base Class
class Base {
    virtual void member() {}
};
  
// Derived Class
class Derived : Base {
};
  
// main() method
int main()
{
  
    // try block
    try {
        Base gfg;
        Derived& rd
            = dynamic_cast<Derived&>(gfg);
    }
  
    // catch block to handle the errors
    catch (bad_cast& bc) {
        cerr << "bad_cast caught: "
             << bc.what() << endl;
    }
  
    return 0;
}


Output:

bad_cast caught: std::bad_cast

Program 2:




// C++ code for std::bad_cast
#include <bits/stdc++.h>
#include <typeinfo>
  
using namespace std;
  
// Base Class
class Base {
    virtual void member() {}
};
  
// Derived Class
class Derived : Base {
};
  
// main() method
int main()
{
  
    // try block
    try {
        Base geeksforgeeks;
        Derived& abc
            = dynamic_cast<Derived&>(
                geeksforgeeks);
    }
  
    // catch block to handle the errors
    catch (bad_cast& a) {
        cerr << "bad_cast caught: "
             << a.what() << endl;
    }
  
    return 0;
}


Output:

bad_cast caught: std::bad_cast

Reference: http://www.cplusplus.com/reference/typeinfo/bad_cast/



Last Updated : 28 May, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads