What is the meaning of using dynamic_cast without any error handling?
Like
struct base
{
virtual void testing() { std::cout<<"base"<<std::endl; }
};
struct derived : public base
{
virtual void testing() { std::cout<<"derived"<<std::endl; }
};
int main()
{
base baseInstance;
derived derivedInstance;
base *bp = &derivedInstance;
base &br = derivedInstance;
//cast pointer with error handling
if(derived *dp = dynamic_cast<derived>(bp)) ...do something with dp
//cast pointer without error handling
derived *dp = dynamic_cast<derived>(bp) ...do something with dp
//cast reference with error handling
try
{
derived *dr = dynamic_cast<derived>(bp);
}
catch(std::bad_cast &ex) {...do something with dr}
//cast reference without error handling
derived *dr = dynamic_cast<derived>(bp);
return 0;
}
If I don't need to do any error handling, should it be a better idea to use static_cast
rather than dynamic_cast? I think it would be more efficient than dynamic_cast.
(Although the best case is without any pointer or reference casting)
Thank you very much.