Exception doesn't work

This is exact copy from tutorial, Why exception isn't thrown / displayed ? I don't see it in console output. Maybe because My compiler isn't configured properly for this to work. I am using "RAD Studio XE5


Note from tutorial:

"dynamic_cast requires the Run-Time Type Information (RTTI) to keep track of dynamic
types. Some compilers support this feature as an option which is disabled by default. This must be enabled for
runtime type checking using dynamic_cast to work properly."

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// dynamic_cast
#include <iostream>
#include <exception>
using namespace std;

class CBase {
	virtual void dummy() {
	}
};

class CDerived : public CBase {
	int a;
};

int main() {
	try {
		CBase * pba = new CDerived;
		CBase * pbb = new CBase;
		CDerived * pd;
		pd = dynamic_cast<CDerived*>(pba);
		if (pd == 0)
			cout << "Null pointer on first type-cast" << endl;
		pd = dynamic_cast<CDerived*>(pbb);
		if (pd == 0)
			cout << "Null pointer on second type-cast" << endl;
	}
	catch (exception& e) {
		cout << "Exception: " << e.what();
	}
	return 0;
}
closed account (zb0S216C)
Have you actually enabled RTTI (if you're not using G++)? Besides, I don't see any reason why this code would throw an exception. Also, you never "delete" the memory you allocated.

Wazzak
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>

struct base { virtual ~base() {} };

struct derived : base {};

int main()
{
    derived d ;
    base b ;

    // dynamic_cast on pointers do not throw (nullptr on failure)
    const base* pointer = &d ;
    std::cout << dynamic_cast<const derived*>(pointer) << '\n' ;

    pointer = &b ;
    std::cout << dynamic_cast<const derived*>(pointer) << '\n' ;

    // dynamic_cast on references throw std::bad_cast on failure
    try
    {
        const base& one = d ;
        const base& two = b ;

        const derived& d1 = dynamic_cast<const derived&>(one) ;
        std::cout << "successs! " << &d1 << '\n' ;

        const derived& d2 = dynamic_cast<const derived&>(two) ;
        std::cout << "also successs! " << &d2 << '\n' ;
    }

    catch( const std::exception& e )
    {
        std::cout << "failed: " << e.what() << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/c146275a1a93264d
@JLBorges:

Thank You. It was all explained in the tutorial I just didn't read the explanation after the source code precisely.

BTW. What a great community You've got here, Thank You once again for Your time.
Last edited on
Topic archived. No new replies allowed.