How to use dynamic_cast to convert object pointer to its subclass in C++

1 Answer

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 *bp;
	Derived *d = new Derived();

	bp = d;
	d = dynamic_cast<Derived*>(bp);

	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
edited Mar 29, 2018 by avibootz

Related questions

2 answers 194 views
2 answers 220 views
1 answer 165 views
165 views asked Apr 12, 2018 by avibootz
1 answer 191 views
1 answer 180 views
1 answer 158 views
...