typeid of an object whose static type is an interface returns the interface

Mark Isaacson via Digitalmars-d digitalmars-d at puremagic.com
Fri Jun 27 14:23:51 PDT 2014


If I have a variable whose static type is an interface and I call
typeid on it, I get the interface back, not the dynamic type.
This seems like confusing behavior. Is this the intended result?

I recognize that one needs some amount of state to perform the
dynamic type lookup, and so it is on that thought that a reason
for this might be based.

My workaround to this issue is shown in the code below, namely,
casting to Object before running typeid produces the expected
result. You can repro the issue by removing that cast.

import std.stdio;
import std.conv;

interface Base {

}

class Derived : Base {

}

void main() {
    Base b = new Derived();
    //1) As is, this prints Derived
    //2) Without the cast, this prints Base -- this is what is
unexpected
    //3) If Base is changed to a class instead of an interface,
this prints Derived regardless of whether or not the cast is in
place
    writeln(text(typeid(cast(Object) b)));
}


More information about the Digitalmars-d mailing list