Why is this cross-cast not allowed?

128 views Asked by At

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

1

There are 1 answers

0
Bathsheba On BEST ANSWER

A static_cast will fail since, informally speaking, Base1 and Base2 are not related.

However a dynamic_cast will work if your classes are polymorphic: which you can achieve by adding virtual destructors:

struct Base1 {virtual ~Base1() = default;};

struct Base2 {virtual ~Base2() = default;};

struct Derived : Base1, Base2 {};

int main()
{
   Derived foo;
   Base1* foo1 = &foo;
   Base2* foo2 =  dynamic_cast<Base2*>(foo1); 
}

This casting from Base1 to Base2 is idiomatic when working with composition (i.e. interfaces).