Skip to content
Related Articles

Related Articles

typeinfo::bad_typeid in C++ with Examples
  • Last Updated : 28 May, 2020

Standard C++ contains several built-in exception classes, typeinfo::bad_typeid is one of them. This is an exception thrown on typeid of null pointer. Below is the syntax for the same:

Header File:

<typeinfo>

Syntax:

class bad_typeid;

Return: The typeinfo::bad_typeid returns a null terminated character that is used to identify the exception.

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



Below are the examples to understand the implementation of typeinfo::bad_typeid in a better way:

Program 1:




// C++ code for std::bad_typeid
#include <bits/stdc++.h>
  
using namespace std;
  
struct gfg {
    virtual void func();
};
  
// main method
int main()
{
    gfg* g = nullptr;
  
    // try block
    try {
        cout << typeid(*g).name()
             << endl;
    }
  
    // catch block to handle the errors
    catch (const bad_typeid& fg) {
        cout << fg.what() << endl;
    }
  
    return 0;
}
Output:
std::bad_typeid

Program 2:




// C++ code for std::bad_typeid
#include <bits/stdc++.h>
  
using namespace std;
  
struct geeksforgeeks {
    virtual void
    A_Computer_Science_Portal_For_Geeks();
};
  
// main method
int main()
{
    geeksforgeeks* gfg = nullptr;
  
    // try block
    try {
        cout << typeid(*gfg).name() << endl;
    }
  
    // catch block to handle the errors
    catch (const bad_typeid& fg) {
        cout << fg.what() << endl;
    }
  
    return 0;
}
Output:
std::bad_typeid

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

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.
My Personal Notes arrow_drop_up
Recommended Articles
Page :