delegate cannot handle polymorphism?

Nub Public nubpublic at gmail.com
Mon Jun 27 04:49:19 PDT 2011


On 6/27/2011 7:08 PM, Michel Fortin wrote:
> On 2011-06-27 03:30:09 -0400, Nub Public <nubpublic at gmail.com> said:
>
>> class B
>> {
>> void fun() { writeln("B"); }
>> }
>>
>> class D : B
>> {
>> override void fun() { writeln("D"); }
>> }
>>
>> void delegate() dg = &b.fun;
>> dg.ptr = cast(void*)d;
>> dg();
>>
>>
>> Compiler: DMD 2.053
>> It prints "B" instead of "D".
>> The equivalent code in C++ prints "D" nicely.
>
> C++ doesn't have delegates, and D doesn't have member function pointers.
> Resolving virtual functions is done while you take its address in D,
> while in C++ the member function pointer type contains holds the vtable
> offset (or several in the case of multiple inheritance) which gets
> resolved only when you call the function.
>
> If you want the C++ behaviour, try using a delegate literal as a
> trampoline that gets the object as a parameter to then call your function:
>
> void delegate(B b) dg = (B b) { b.fun(); };
>
> dg(d);
>


Thank you. That was very helpful.

What's the rational for this behavior though? Resolving the address of a 
virtual function at compile time seems a little counter-intuitive to me.
I guess this way is slightly more efficient.


More information about the Digitalmars-d mailing list