www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - No implicitly convert derived ptr to base ptr?

reply "Nick Sabalausky" <SeeWebsiteToContactMe semitwist.com> writes:
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?
Apr 24 2012
next sibling parent Jonathan M Davis <jmdavisProg gmx.com> writes:
On Wednesday, April 25, 2012 01:50:51 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?
Well, given that pointers aren't polymorphic at all, it's not all that great an idea in general to assign a derived class object to a base class pointer, so it's arguably a good thing that it doesn't work, but I am a bit surprised that it doesn't work. - Jonathan M Davis
Apr 24 2012
prev sibling parent Timon Gehr <timon.gehr gmx.ch> writes:
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)*.
Apr 24 2012