No implicitly convert derived ptr to base ptr?
Timon Gehr
timon.gehr at gmx.ch
Tue Apr 24 23:23:17 PDT 2012
On 04/25/2012 07:50 AM, Nick Sabalausky wrote:
> The compiler rejects this:
>
> class Base {}
> class Derived : Base {}
>
> void main()
> {
> Base* basePtr;
> Derived* derivedPtr;
>
> basePtr = derivedPtr; // ERROR
> }
>
> Is that really correct that it shouldn't be allowed?
>
>
Yes it is. It was allowed a number of releases ago, but that bug has
since been fixed.
Example that shows unsoundness:
class Base {}
class Derived1 : Base {}
class Derived2 : Base {}
void main() {
Derived1 d1;
Base* basePtr = &d1;
*basePtr = new Derived2;
assert(typeid(d1)==typeid(Derived2) && !is(Derived2: typeof(d1));
}
Note that the conversion succeeds if the tail of the pointer is not
mutable, eg Derived* implicitly converts to const(Base)*.
More information about the Digitalmars-d-learn
mailing list