PDA

View Full Version : dynamic_cast not working



kloffy
11th October 2007, 22:34
Do I need to recompile qmake with the exceptions, rtti and stl flags to get dynamic_cast to work with QT? I'm using Visual C++ 2005 and the /GR flag is enabled (by default).

I'm asking because have implemented a simple Composite Pattern (http://en.wikipedia.org/wiki/Composite_pattern) and I need to find out whether the Component is a Leaf or a Composite. This is what I would like to do:

try
{
Leaf* leaf = dynamic_cast<Leaf*>(component);
//A Leaf
}
catch (std::bad_cast e)
{
//Not a Leaf
}
However, in practice the exception is never thrown and the program dies because of memory access violations.

marcel
11th October 2007, 23:01
If the cast fails then leaf will be NULL. No need to catch any exceptions. Just test the leaf.

kloffy
11th October 2007, 23:07
Ahhh, I should really learn to read...

The value of a failed cast to pointer type is the null pointer. A failed cast to reference type throws a bad_cast Exception.Thanks for the heads up!