Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

typeinfo::bad_cast in C++ with Examples

  • Last Updated : 28 May, 2020

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:

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
<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/




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!