user13756099
user13756099

Reputation:

std::bad_cast vs NULL, what's the difference?

Why we need std::bad_cast when It returns Null when it fails?

I learnt that when dynamic_cast fails it returns Null So I could check if Null was returned it means an error happened.

But why std::bad_cast exception was added to C++?

Upvotes: 1

Views: 283

Answers (2)

Cory Kramer
Cory Kramer

Reputation: 117886

std::bad_cast is thrown when casting a reference

With a pointer cast, as you mentioned you could use dynamic_cast

Base* b = dynamic_cast<Base*>(a);  // could return nullptr

With a reference, you cannot assign nullptr

try
{
    Base& b = dynamic_cast<Base&>(a);
} 
catch(const std::bad_cast& e)
{
    std::cout << e.what() << '\n';
}

so std::bad_cast provides a mechanism to know that the cast failed.

Upvotes: 1

NathanOliver
NathanOliver

Reputation: 180660

Because you can't have a null reference. A dynamic_cast<T*> can return nullptr as a failure but dynamic_cast<T&> can't, since you're returning a reference to the object. For that case you need an exception to know that the cast failed.

Upvotes: 6

Related Questions