Re: why dynamic_cast fail here?
pietromas@gmail.com wrote:
In the example below, why does the dynamic_cast fail (return NULL)? It
should be able to cast between sibling classes ...
No, it should not and is not. See [5.2.7] for the conversions supported by
dynamic_cast<>. Specifically [5.2.7/8]
The run-time check logically executes as follows:
? If, in the most derived object pointed (referred) to by v, v points
(refers) to a public base class subobject of a T object, and if only one
object of type T is derived from the sub-object pointed (referred) to by
v, the result is a pointer (an lvalue referring) to that T object.
? Otherwise, if v points (refers) to a public base class sub-object of the
most derived object, and the type of the most derived object has a base
class, of type T, that is unambiguous and public, the result is a
pointer (an lvalue referring) to the T sub-object of the most derived
object.
? Otherwise, the run-time check fails.
#include <iostream>
class A
{
public:
virtual const int get() const = 0;
};
class B : public A
{
public:
virtual const int get() const { return 0; }
};
class C : public A
{
public:
virtual const int get() const { return 1; }
};
int main()
{
A *a;
a = new B();
std::cout << a->get() << std::endl;
a = dynamic_cast<C*>(a);
The dynamic type of *a is B. The dynamic_cast<> is specifically designed to
catch the error in trying to regard this object as anything that it not
truly is. Therefore, dynamic_cast<> will fail if you cast the object to any
type that is not a base class of its dynamic type.
if(a)
std::cout << a->get() << std::endl;
return 0;
}
Best
Kai-Uwe Bux