“Now my question is why is
static_cast
working here.”
There is no reason why it should not work. The types are related by class derivation, and that’s known by the compiler. Essentially static_cast
is restricted to do or undo any implicit conversion, and you do have an implicit conversion from der*
to base*
.
“I read that
static_cast
s cannot cast through polymorphic types.”
That’s just balderdash.
“[snip] Could anyone give an example where
static cast
would fail anddynamic cast
would pass?”
struct A { virtual ~A(){} };
struct B { virtual ~B(){} };
struct T: A, B {};
auto main()
-> int
{
T o;
A& oA = o;
//B& oB = static_cast<B&>( oA ); //! This won't compile, unrelated types.
B& oB = dynamic_cast<B&>( oA );
}