www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Getting most derived type of object that implements interface

reply cc <cc nevernet.com> writes:
I'm having trouble getting the full name of an object of a class 
that implements an interface, using typeid() or .classinfo, the 
behavior seems to be different from that of a class that simply 
derives other classes.

interface FooInterface {}
class BarImplementsInterface : FooInterface {}

class FooBaseClass {}
class BarDerivedClass : FooBaseClass {}

void main() {
	FooInterface a = new BarImplementsInterface();
	FooBaseClass b = new BarDerivedClass();
	writefln("a class: %s", a.classinfo.name);
	writefln("b class: %s", b.classinfo.name);
}

Output:
a class: test.FooInterface
b class: test.BarDerivedClass


I expected "a class: test.BarImplementsInterface" as the result 
output.. Am I expecting the wrong behavior?  Is there a preferred 
way to do this?
Jul 25 2016
next sibling parent reply Kagamin <spam here.lot> writes:
Cast it to Object:
	FooInterface a = new BarImplementsInterface();
	FooBaseClass b = new BarDerivedClass();
	Object o = cast(Object)a;
	writefln("a class: %s", a.classinfo.name);
	writefln("b class: %s", b.classinfo.name);
	writefln("o class: %s", o.classinfo.name);
Jul 25 2016
next sibling parent Steven Schveighoffer <schveiguy yahoo.com> writes:
On 7/25/16 5:54 AM, Kagamin wrote:
 Cast it to Object:
     FooInterface a = new BarImplementsInterface();
     FooBaseClass b = new BarDerivedClass();
     Object o = cast(Object)a;
     writefln("a class: %s", a.classinfo.name);
     writefln("b class: %s", b.classinfo.name);
     writefln("o class: %s", o.classinfo.name);
Yes, for the unrelated reason that COM objects may not be D objects, interfaces that can only possibly be D Objects don't implicitly cast to Object. -Steve
Jul 25 2016
prev sibling parent cc <cc nevernet.com> writes:
Ahh I see, thanks guys.
Jul 25 2016
prev sibling parent ketmar <ketmar ketmar.no-ip.org> writes:
yep, cast it. without the cast, compiler assuming that it knows 
the type in runtime, and is using well-known classinfo address 
instead of really looking into instance for that.
Jul 25 2016