digitalmars.D.learn - No implicitly convert derived ptr to base ptr?
- Nick Sabalausky (10/10) Apr 24 2012 The compiler rejects this:
- Jonathan M Davis (6/20) Apr 24 2012 Well, given that pointers aren't polymorphic at all, it's not all that g...
- Timon Gehr (15/25) Apr 24 2012 Yes it is. It was allowed a number of releases ago, but that bug has
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
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
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








 
  
  
 
 Jonathan M Davis <jmdavisProg gmx.com>
 Jonathan M Davis <jmdavisProg gmx.com> 