Passing a derived class where base class is defined as ref parameter

chopchop bullshiiii at gmail.com
Tue Dec 14 16:27:20 UTC 2021


On Tuesday, 14 December 2021 at 05:38:17 UTC, Tejas wrote:
> On Monday, 13 December 2021 at 22:30:59 UTC, Adam D Ruppe wrote:
>> On Monday, 13 December 2021 at 22:06:45 UTC, chopchop wrote:
>>> If I remove the ref, it works as expected, that is to say I 
>>> can give a derived class as parameter.
>>
>> Why are you using the ref to begin with?
>>
>>> What the logic here?
>>
>> Consider this:
>>
>>
>> class C : A {}
>>
>> void incr(ref A a) {
>>    a = new C;
>> }
>>
>> B b = new B;
>> incr(b);
>> // oops b now got rebound to a C instead of to a B, which 
>> breaks everything
>
> But `B` is not a child of `A`, why should it be accepted in a 
> function that accepts `A` as a parameter? It's not implicitly 
> convertible to `A`

Tejas, I think you should not read Adam's example as standalone, 
obviously he is implicitly reusing the definition of B in my 
first post, so B is indeed a child of A.


More information about the Digitalmars-d-learn mailing list