Consider this simple example:
struct Base1 {};
struct Base2 {};
struct Derived : public Base1, public Base2 {};
int main()
{
Derived foo;
Base1* foo1 = &foo;
Base2* foo2 = static_cast<Base2*>(foo1);
}
I get:
Error: static_cast from 'Base1 *' to 'Base2 *', which are not related by inheritance, is not allowed
The compiler should have enough information to figure out that Base2 can be reached from Derived without RTTI (dynamic_cast) and having me to do:
Derived* foo3 = static_cast<Derived*>(foo1);
Base2* foo2 = foo3;
Why isn't this allowed? (One could argue that the compiler doesn't know if foo1 is of Derived type, but static_cast doesn't check the type anyway even when converting from Base1 to Derived for example)
Note: This question is similiar to mine, but it's not quite the same because here we are cross-casting base classes, not derived ones
A
static_castwill fail since, informally speaking,Base1andBase2are not related.However a
dynamic_castwill work if your classes are polymorphic: which you can achieve by adding virtual destructors:This casting from
Base1toBase2is idiomatic when working with composition (i.e. interfaces).