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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

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 154 views
1 answer 175 views
1 answer 129 views
1 answer 220 views
1 answer 149 views
1 answer 202 views
1 answer 161 views
...