Reputation: 5787
Is there any reason against using Foo* foo = &dynamic_cast<Foo&>(*ptrFoobase);
? I want it to throw bad_cast if the cast is incorrect, and saves an additional check for the pointer against zero.
Upvotes: 0
Views: 128
Reputation: 476960
There isn't a strict universal reason why you shouldn't do it, but it's sort of ugly and hard to read.
If you have decided that throwing an exception is the right thing to do, you should probably revisit your other design choices: Why do you need a pointer at all? If you stick with references, there's no problem: Foo & foo = dynamic_cast<Foo&>(fooBaseRef);
.
Personally, I'd say that if you have naked pointers in C++, you're in some sort of legacy mindset, so you should probably just add the null-check and throw manually. On the other hand, if you want to go for idiomatic, modern C++, prefer references all the way, and you get your exception for free.
Upvotes: 3