How to dynamically call class virtual method dynamically

anonymous anonymous at example.com
Tue Apr 1 12:42:36 PDT 2014


On Tuesday, 1 April 2014 at 19:00:18 UTC, Frustrated wrote:
> A a = new B;
[...]
Now suppose B implements That as a virtual method that doesn't
exist in A.
[...]
> e.g., typeof(cast(Object)a) returns B, right?

No, it's Object. You're looking for typeid which returns a 
TypeInfo [1] which is runtime information about the type. For 
classes that's for the most derived one (here: B).

> I could be mistaken but isn't `A a = new B` just a facade and a 
> really is of type B? If so, isn't there a way to get the true 
> type of a at runtime? If so, then can't we cast a to its true 
> type at runtime and access its members properly?

Yes, all true. But you need the target type at compile time to 
cast.

> e.g., suppose truecast(a) returns a as the actual object that a 
> was created as(in this case B, not A). Then truecast(a).That() 
> would work.

When different implementations of A have different Thats, they 
are not related in any way. And the compiler doesn't know about 
(possibly future) implementations when working on code that uses 
just the interface A. So, as far as I can see, truecast(a).That() 
would have to be a string lookup at runtime.

And then the members' types would be dynamic, too, of course. I 
have no idea how one would go about that. My best guess is that 
all of D's type system would have to be duplicated at runtime.

[1] http://dlang.org/phobos/object.html#TypeInfo


More information about the Digitalmars-d-learn mailing list