How to use dynamic_cast between base class and derived class in C++

2 Answers

0 votes
#include <iostream>
#include <exception>

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

class Base { 
	virtual void method() { 
		cout << "class Base" << endl; 
	} 
};
class Derived : public Base { 
	virtual void method() {
		cout << "class Derived" << endl;
	}
};

int main() 
{
	try 
	{
		Base *pb = new Derived;
		Derived *pd;

		pd = dynamic_cast<Derived*>(pb);
		
		cout << pb << endl;
		cout << pd << endl;
	}
	catch (std::exception &e) { 
		cout << "Exception: " << e.what();
	}

	return 0;
}


/*
run:

00736038
00736038

*/

 



answered Mar 5, 2018 by avibootz
0 votes
#include <iostream>
#include <exception>

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

class Base { 
	virtual void method() { 
		cout << "class Base" << endl; 
	} 
};
class Derived : public Base { 
	virtual void method() {
		cout << "class Derived" << endl;
	}
};

int main() 
{
	try 
	{
		Base *pb = new Base;
		Derived *pd;

		pd = dynamic_cast<Derived*>(pb);
		
		cout << pb << endl;
		cout << pd << endl;
	}
	catch (std::exception &e) { 
		cout << "Exception: " << e.what();
	}

	return 0;
}


/*
run:

00386038
00000000

*/

 



answered Mar 5, 2018 by avibootz

Related questions

1 answer 173 views
1 answer 196 views
1 answer 144 views
1 answer 241 views
1 answer 159 views
1 answer 221 views
1 answer 179 views
...