Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,094 questions

40,775 answers

573 users

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 64 views
2 answers 109 views
...