[Understanding] Classes and delegate inheritance vs function pointers

Q. Schroll qs.il.paperinik at gmail.com
Sun Jan 10 00:44:26 UTC 2021


On Saturday, 9 January 2021 at 21:57:43 UTC, sighoya wrote:
> On Saturday, 9 January 2021 at 20:20:38 UTC, Q. Schroll wrote:
>> That's not what I mean. You copy the reference. That's not 
>> what referencing meant.
>>
>>   Derived d = new Derived();
>>   Base* bp = &d; // fails
>>   const(Base) cbp = &d; // compiles.
>
> Generally, allowing covariant assignment for the Ptr<T>, i.e. 
> T*, type only in case of const T* strikes me. IMHO, both should 
> be synchronously (dis)allowed.

I'm unsure what you mean.

If you have an array `cars` of type Car[], you can treat it as a 
const(Vehicle)[] because reading a Car as a Vehicle is 
unproblematic. But if it could bind to Vehicle[], its elements 
could be written arbitrary Vehicles. Say it worked, then:

   Car[] cars = ...;
   Vehicle[] vehicles = cars;
   vehicles[0] = new Boat; // err...
   // cars[0] is a Boat now!?

Now what? Do what Java does and throw an Exception? Or use const 
to prevent mutation?

> Because D doesn't support co(ntra)variance, it should be both 
> disallowed?

Imagine for a moment, `const` were named `read_only` and there 
were a specifier `write_only`. That looks silly, but makes sense 
in some cases:

   Vehicle[] vehicles = ...;
   write_only(Car)[] cars = vehicles; // WTF!?
   cars[i] = new Car; // wait, that's actually okay...

Because write_only isn't a thing in D, contravariance is an odd 
thing to get your a D mind around.

> Otherwise, because D already support the const case, why not 
> the non const case?

The non-const case makes no sense.

> Are there any alignment issues supporting the non const case?

It's not alignment, probably. (Maybe it is, I know almost nothing 
about alignment, to be honest.) Among other things, in the 
non-const case, as you call it, the type system cannot guarantee 
anymore that stuff that is typed some way actually contains those 
objects.
It is one of the major issues Java has and why everyone and their 
mom tells you not to use Java's arrays and instead use List or 
similar well-behaved constructs.

BTW, my question wasn't about classes at all. I used them as an 
illustration what works and asked why (seemingly) the same thing 
doesn't with function pointers.


More information about the Digitalmars-d-learn mailing list