delegate cannot handle polymorphism?

Michel Fortin michel.fortin at michelf.com
Tue Jun 28 16:18:16 PDT 2011


On 2011-06-27 07:49:19 -0400, Nub Public <nubpublic at gmail.com> said:

> 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.

The address for a virtual function isn't necessarily resolved at 
compile time. It is resolved at the point where you use the address-of 
operator, and that'll check the vtable at runtime if necessary.

In D:

	B b = new D;
	auto dg = &b.foo; // address is resolved at runtime by looking at the vtable
	dg(); // calls D.foo

In C++:

	void (B::*fptr)() = &B::foo;
	B b = new D;
	b.*fptr(); // vtable lookup here, calls D.foo


> I guess this way is slightly more efficient.

It certainly is if you call the delegate more often than you create one.

-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/



More information about the Digitalmars-d mailing list