Both clang 3.5.0 and g++ 4.9.0 compile the following code fine (with -std=c++11 -Wall -Wextra -pedantic-errors
) and the program outputs true
:
#include <iostream>
struct A
{
virtual ~A() = default;
};
struct B
{
virtual ~B() = default;
};
struct C : A, B
{
virtual ~C() = default;
};
int main()
{
C c;
A* ap = &c;
B* bp = dynamic_cast<B*>(ap);
std::cout << std::boolalpha << (bp != nullptr) << std::endl;
}
If the cast is successful, dynamic_cast returns a value of type new-type. If the cast fails and new-type is a pointer type, it returns a null pointer of that type. If the cast fails and new-type is a reference type, it throws an exception that matches a handler of type std::bad_cast.
The primary purpose for the dynamic_cast operator is to perform type-safe downcasts. A downcast is the conversion of a pointer or reference to a class A to a pointer or reference to a class B , where class A is a base class of B .
dynamic_cast will no longer throw an exception when type-id is an interior pointer to a value type, with the cast failing at runtime. The cast will now return the 0 pointer value instead of throwing.
The dynamic_cast operator can be used to cast to reference types. C++ reference casts are similar to pointer casts: they can be used to cast from references to base class objects to references to derived class objects.
Yes. That's sometimes known as cross-casting, and will succeed if they are both base sub-objects of the same derived object, as they are here.
dynamic_cast
is necessary, since the conversion needs the run-time information that both are part of a C
object. To statically cast, you'd have to explicitly convert to C*
first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With