Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it valid to cast from A* to B* via dynamic_cast when A and B haven't a common ancestor?

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;
}
like image 320
Constructor Avatar asked Oct 15 '14 14:10

Constructor


People also ask

What is the behavior of dynamic_cast when down casting is detected on pointers?

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.

What is the use of dynamic_cast operator in C++?

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 .

Can dynamic_cast throw exception?

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.

Can dynamic cast be used with references?

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.


1 Answers

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.

like image 70
Mike Seymour Avatar answered Oct 13 '22 00:10

Mike Seymour