typeinfo::bad_cast in C++ with Examples

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

bad_cast caught: std::bad_cast

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

bad_cast caught: std::bad_cast

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

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.