I can understand why dynamic_cast does work in this case :
#include <iostream>
struct A{
virtual ~A() = default;
};
struct B {
virtual ~B() = default;
};
struct C : A, B{};
void f(const A &a) {
if(auto p = dynamic_cast<const B*>(&a))
std::cout << "a is a B" << std::endl;
}
int main() {
f(C{});
return 0;
}
But why if you remove the polymorphism from B it still works :
#include <iostream>
struct A{
virtual ~A() = default;
};
struct B {
};
struct C : A, B{};
void f(const A &a) {
if(auto p = dynamic_cast<const B*>(&a))
std::cout << "a is a B" << std::endl;
}
int main() {
f(C{});
return 0;
}
Is it because dynamic_cast must only know the real type of the object you give has a parameter (as dynamic_cast<void*>
/ typeid would do), and after it knows the real type, it knows if the type is derived from a non polymorphic base?