I agree with @j6t's answer, but here is an expanded reasoning with standard references.
The special behavior of dynamic_cast
for objects under construction and destruction is described by [class.cdtor]/5 of the C++17 standard (final draft) and equivalently by previous standard versions.
In particular it says:
When a dynamic_cast
is used [...] in a destructor, [...], if the operand of the dynamic_cast
refers to the object under construction or destruction, this object is considered to be a most derived object that has the type of the [...] destructor's class. If the operand of the dynamic_cast
refers to the object under [...] destruction and the static type of the operand is not a pointer to or object of the [...] destructor's own class or one of its bases, the dynamic_cast results in undefined behavior.
The undefined behavior does not apply here, since the operand is the expression this
, which trivially has the type of a pointer to the destructor's own class since it appears in the destructor itself.
However, the first sentence states that the dynamic_cast
will behave as if *this
was a most derived object of type Base2
and therefore the cast to Base1
can never succeed, because Base2
is not derived from Base1
, and dynamic_cast<Base1*>(this)
will always return a null pointer, resulting in the behavior you are seeing.
cppreference.com states that the undefined behavior happens if the destination type of the cast is not the type of the destructor's class or one of its bases, rather than having this apply to the operands type. I think that is just a mistake. Probably the mention of "new-type" in bullet point 6 was supposed to say "expression", which would make it match my interpretation above.
!
– Bluebilldynamic_cast
behave differently in constructors and destructors? – Avellaneda