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:
#include <bits/stdc++.h>
#include <typeinfo>
using namespace std;
class Base {
virtual void member() {}
};
class Derived : Base {
};
int main()
{
try {
Base gfg;
Derived& rd
= dynamic_cast <Derived&>(gfg);
}
catch (bad_cast& bc) {
cerr << "bad_cast caught: "
<< bc.what() << endl;
}
return 0;
}
|
Output:
bad_cast caught: std::bad_cast
Program 2:
#include <bits/stdc++.h>
#include <typeinfo>
using namespace std;
class Base {
virtual void member() {}
};
class Derived : Base {
};
int main()
{
try {
Base geeksforgeeks;
Derived& abc
= dynamic_cast <Derived&>(
geeksforgeeks);
}
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
Share your thoughts in the comments
Please Login to comment...