Down cast and try catch
Apr 14, 2016 at 5:39am UTC
Hey Guys,
Two questions in one. First I'm down casting, from what I've read it will
slice off not know about the other stuff, move everything possible up the tree?
Second I haven't used try catch in this decade and I'm out of practice, will nesting a try within a catch work? Additionally is what I'm catching the correct thing to be using in this case?
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 37 38 39 40
class Foo
{
virtual void doSomething(int ) = 0;
};
class Bar :public Foo
{
struct A{ int k; } a;
void doSomething(int );
};
class Baz: public Foo
{
struct B{ unsigned int p; } b;
void doSomething(int );
};
class Gux
{
bool handleFoo(Foo* takeCare)
{
try
{
handleBar(dynamic_cast <Bar*>(takeCare));
}
catch (const std::invalid_argument& dang)
{
try
{
handleBaz(dynamic_cast <Baz*>(takeCare));
}
catch (const std::invalid_argument& doubleDang)
{
return false ;
}
}
return true ;
}
void handleBaz(Baz*){}
void handleBar(Bar*){}
};
Thanks for any input
Last edited on Apr 14, 2016 at 5:47am UTC
Apr 14, 2016 at 6:43am UTC
Who does throw? The cast doesn't. The cast returns null on failure.
1 2 3 4 5 6 7 8 9 10 11 12
bool handleFoo( Foo* takeCare ) {
if ( Bar * p = dynamic_cast <Bar*>(takeCare) ) {
handleBar( p );
}
else if ( Baz * p = dynamic_cast <Baz*>(takeCare) ) {
handleBaz( p );
}
else {
return false ;
}
return true ;
}
Apr 14, 2016 at 8:54am UTC
Why do you want to cast at all?
1 2 3 4
bool handleFoo( Foo* takeCare )
{
takeCare->doSomething(someInt);
}
Do handleBaz() and handleBar() check for null pointers - in case the cast fails?
Apr 14, 2016 at 8:50pm UTC
Good point. Even better example
Why do you want to cast at all?
I need to get at the data members of Baz and Bar. So far I have handleBaz() working as intended.
Do handleBaz() and handleBar() check for null pointers - in case the cast fails?
No, I realize now how silly it was to do that
Topic archived. No new replies allowed.