Conversion from Derived** to Base**

后端 未结 3 722
终归单人心
终归单人心 2020-12-01 20:59

I was reading this and unfortunately could not understand in depth why the compiler does not allow conversion from Derived** to Base**. Also I have seen this which gives no

3条回答
  •  心在旅途
    2020-12-01 21:39

    It's basically the same reason why a bowl of bananas is not a bowl of fruits. If a bowl of bananas were a bowl of fruits, you could put an apple into the bowl, and it would no longer be a bowl of bananas.

    As long as you only inspect the bowl, the conversion is harmless. But as soon as you start modifying it, the conversion becomes unsafe. This is the key point to bear in mind. (This is the precise reason why the immutable Scala collections actually allow the conversion, but the mutable collections prohibit it.)

    Same with your example. If there was a conversion from Derived** to Base**, you could put a pointer to an apple were the type system promised only a pointer to a banana could exist. Boom!

提交回复
热议问题