user3308043
user3308043

Reputation: 827

"Safe" dynamic cast?

I'm familiar with how to do a dynamic cast in C++, as follows:

myPointer = dynamic_cast<Pointer*>(anotherPointer);

But how do you make this a "safe" dynamic cast?

Upvotes: 5

Views: 2677

Answers (3)

Tony Delroy
Tony Delroy

Reputation: 106096

Most ways in which you might attempt to abuse dynamic_cast result in a compiler error (for example, trying to cast to a type that's not in a related polymorphic hierarchy).

There are also two runtime behaviours for times when you effectively use dynamic_cast to ask whether a particular pointer actually addresses an object of a specific derived type:

if (Derived* p = dynamic_cast<Derived*>(p_base))
{
    ...can use p in here...
}
else
    ...p_base doesn't point to an object of Derived type, nor anything further
       derived from Derived...

try
{
    Derived& d = dynamic_cast<Derived&>(*p_base);
    ...use d...
}
catch (std::bad_cast& e)
{
    ...wasn't Derived or further derived class...
}

The above is "safe" (defined behaviour) as long as p_base is either nullptr/0 or really does point to an object derived from Base, otherwise it's Undefined Behaviour.

Additionally, there is a runtime-unsafe thing you can do with a dynamic_cast<>, yielding Undefined Behaviour:

  • Standard 12.7/6: "If the operand of the dynamic_cast refers to the object under construction or destruction and the static type of the operand is not a pointer to or object of the constructor or destructor’s own class or one of its bases, the dynamic_cast results in undefined behavior.". The Standard provides an example to illustrate this.

Upvotes: 1

R Sahu
R Sahu

Reputation: 206577

Q But how do you make this a "safe" dynamic cast?

A It will be a safe dynamic cast as long as the argument to dynamic_cast is a valid pointer (including NULL). If you pass a dangling pointer or a value that is garbage, then the call to dynamic_cast is not guaranteed to be safe. In fact, the best case scenario is that the run time system throws an exception and you can deal with it. The worst case scenario is that it is undefined behavior. You can get one behavior now and a different behavior next time.

Upvotes: 0

humam
humam

Reputation: 191

When dynamic_cast cannot cast a pointer because it is not a complete object of the required class it returns a null pointer to indicate the failure. If dynamic_cast is used to convert to a reference type and the conversion is not possible, an exception of type bad_cast is thrown instead.

Upvotes: 8

Related Questions