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:
#include <bits/stdc++.h>
using namespace std;
struct gfg {
virtual void func();
};
int main()
{
gfg* g = nullptr;
try {
cout << typeid (*g).name()
<< endl;
}
catch ( const bad_typeid& fg) {
cout << fg.what() << endl;
}
return 0;
}
|
Program 2:
#include <bits/stdc++.h>
using namespace std;
struct geeksforgeeks {
virtual void
A_Computer_Science_Portal_For_Geeks();
};
int main()
{
geeksforgeeks* gfg = nullptr;
try {
cout << typeid (*gfg).name() << endl;
}
catch ( const bad_typeid& fg) {
cout << fg.what() << endl;
}
return 0;
}
|
Reference: http://www.cplusplus.com/reference/typeinfo/bad_typeid/
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...