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

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Sun Jun 29 20:33:23 PDT 2014


On Sun, 29 Jun 2014 01:07:11 -0400, Kapps <opantm2+spam at gmail.com> wrote:

> On Friday, 27 June 2014 at 21:23:52 UTC, Mark Isaacson wrote:
>> 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.
>
> Interfaces are not necessarily Objects (particularly with the case of  
> IUnkown or extern(C++)), and are handled somewhat differently from  
> objects.

As I've said many times, instances of D interfaces are necessarily  
Objects. Any D class that implements a D interface is a D object, and  
should implicitly cast to Object.

> When you cast to Object, you're actually subtracting a few bytes from  
> the pointer to get back to the Object, so technically the variable  
> refers not to Object but to the interface. It is a bit odd (along with  
> some of the other side-effects), but it does make some sense since  
> you're referring to the interface and not to an Object.

Correct. It would be a trivial extra-step of subtraction to get the  
TypeInfo of the class itself.

> That being said, I'm not 100% sure whether this is the intended  
> behaviour when you actually do point to a class derived from Object.

It is the intended behavior. And I think your reasoning of the IUnknown  
problem is the intended reasoning. And I think it's wrong :)

-Steve


More information about the Digitalmars-d mailing list