Converting Derived** to Base** and Derived* to Base*

前端 未结 6 832

Ok, I was reading through this entry in the FQA dealing about the issue of converting a Derived** to a Base** and why it is forbidden, and I got th

6条回答
  •  自闭症患者
    2020-12-10 20:29

    *b = Base(3); // Ouch!
    

    Here the object at *b really is a B, it's the base sub-object of *d. Only that base sub-object gets modified, the rest of the derived object isn't changed and d still points to the same object of the derived type.

    You might not want to allow the base to be modified, but in terms if the type system it's correct. A Derived is a Base.

    That's not true for the illegal pointer case. A Derived* is convertible to Base* but is not the same type. It violates the type system.

    Allowing the conversion you're asking about would be no different to this:

    Derived* d;
    Base b;
    d = &b;
    d->x;
    

提交回复
热议问题