delegate bug?
Jacob Carlborg
doob at me.com
Fri Nov 9 06:25:00 PST 2012
On 2012-11-09 14:36, Jack Applegame wrote:
> This code:
>
> import std.stdio;
> class A {
> void func() { writeln("A"); }
> }
> class B : A {
> override void func() { writeln("B"); }
> }
> void main() {
> A a = new A;
> B b = new B;
>
> auto dg = &a.func;
> dg();
>
> dg.ptr = cast(void*)b;
> dg();
> }
>
> outputs:
> A
> A
>
> but expected:
> A
> B
This is expected behavior. Delegates do not perform any dynamic
dispatch. The method that is called is chosen when the delegate is
created, i.e. "auto dg = &a.func;"
You can workaround this by calling another method in "A" that will call
the actual method you want to call, something like this:
class A
{
void resolveVirtualCall ()
{
func();
}
}
auto dg = &a.resolveVirtualCall;
--
/Jacob Carlborg
More information about the Digitalmars-d-learn
mailing list