Implicit conversion from class in parent class fails?

Ali Çehreli acehreli at yahoo.com
Sat Jun 16 12:55:03 PDT 2012


On 06/16/2012 11:55 AM, Andrew Wiley wrote:
> On Sat, Jun 16, 2012 at 11:52 AM, Namespace<rswhite4 at googlemail.com>  wrote:
>> Why work this:
>>
>> [code]
>> class Foo { }
>> class Bar : Foo { }
>> class Quatz : Bar { }
>>
>> void foo(Foo f) {
>>
>> }
>>
>> void main() {
>>         Foo f = new Foo();
>>         Foo f2;
>>
>>         foo(f);
>>         foo(f2);
>>
>>         Bar b = new Bar();
>>         Bar b2;
>>
>>         foo(b);
>>         foo(b2);
>>
>>         Quatz q = new Quatz();
>>         Quatz q2;
>>
>>         foo(q);
>>         foo(q2);
>> }
>> [/code]
>>
>> but not:
>>
>> [code]
>> import std.stdio;
>>
>> class Foo { }
>> class Bar : Foo { }
>> class Quatz : Bar { }
>>
>> void bar(Foo[] fs) {
>>
>> }
>>
>> void main() {
>>         Foo[] fs = [new Foo()];
>>         Foo[] fs2;
>>
>>         bar(fs);
>>         bar(fs2);
>>
>>         Bar[] bs = [new Bar()];
>>         Bar[] bs2;
>>
>>         bar(bs);
>>         bar(bs2);
>>
>>         Quatz[] qs = [new Quatz()];
>>         Quatz[] qs2;
>>
>>         bar(qs);
>>         bar(qs2);
>> }
>> [/code]
>>
>> I think that should work also.
>
> The problem is that this would also work:
>   [code]
>   import std.stdio;
>
>   class Foo { }
>   class Bar : Foo { }
>   class Quatz : Bar { }
>
>   void bar(Foo[] fs) {
>      fs[0] = new Foo(); //<-- OH NOES
>   }
>
> void main() {
>          Foo[] fs = [new Foo()];
>          Foo[] fs2;
>
>          bar(fs);
>          bar(fs2);
>
>          Bar[] bs = [new Bar()];
>          Bar[] bs2;
>
>          bar(bs);
>          bar(bs2);
>
>          Quatz[] qs = [new Quatz()];
>          Quatz[] qs2;
>
>          bar(qs);
>          bar(qs2);
> }
>   [/code]

The following is a shorter example, which happens to also produce a more 
educating error message:

import std.stdio;

class Foo { }
class Bar : Foo { }
class Quatz : Bar { }

void zar(ref Foo fs) {// <-- ref
     fs = new Quatz(); // <-- OH NOES
}

void main()
{
     auto b = new Bar();
     zar(b);    // <-- Error: cast(Foo)b is not an lvalue
}

After all of the above, a const reference works as Namespace expects:

import std.stdio;

class Foo { }
class Bar : Foo { }
class Quatz : Bar { }

void zar(const Foo[] fs) {    // <-- const makes it work
     // ...
}

void main()
{
     zar([ new Bar() ]);
}

Ali

-- 
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html


More information about the Digitalmars-d-learn mailing list