How to use dynamic_cast with try and catch in C++

2 Answers

0 votes
#include <typeinfo>
#include <iostream>

using std::cout;
using std::endl;

class Base {
public:
	Base() {};
	virtual ~Base() {}
};

class Derived : public Base {
public:
	Derived() {}
	virtual ~Derived() {}
};

int main() 
{
	Base base;
	Derived derived;

	Base &bref = base;

	try {
		Derived &dr = dynamic_cast<Derived&>(bref);
	}
	catch (const std::bad_cast& e)
	{
		std::cout << e.what() << endl;
	}

	return 0;
}


/*
run:

Bad dynamic_cast!

*/

 



answered Mar 29, 2018 by avibootz
0 votes
#include <typeinfo>
#include <iostream>

using std::cout;
using std::endl;

struct A { virtual ~A() {} };
struct B { virtual ~B() {} };

int main()
{
	B b;
	try {
		A &ref = dynamic_cast<A&>(b);
	}
	catch (const std::bad_cast &e)
	{
		cout << e.what() << endl;
	}

	return 0;
}


/*
run:

Bad dynamic_cast!

*/

 



answered Mar 29, 2018 by avibootz

Related questions

1 answer 146 views
1 answer 212 views
2 answers 301 views
3 answers 335 views
335 views asked Jan 3, 2016 by avibootz
...