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

Tejas notrealemail at gmail.com
Tue Dec 14 05:38:17 UTC 2021


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`


More information about the Digitalmars-d-learn mailing list