Find out most derived class in base class

Steven Schveighoffer schveiguy at yahoo.com
Mon Nov 22 09:09:19 PST 2010


On Fri, 19 Nov 2010 16:48:50 -0500, Michal Minich  
<michal.minich at gmail.com> wrote:

> On Fri, 19 Nov 2010 21:37:45 +0000, div0 wrote:
>
>> On 19/11/2010 21:22, Jonathan M Davis wrote: At runtime, the runtime
>> type info for classes forms a DAG.
>>>>
>>>> As D only allows single inheritance it should be trivial to find the
>>>> most derived class, though the runtime doesn't currently offer a
>>>> function for this.
>>>
>>> Just because an object is able to know what its actual type is - or
>>> even its base classes - does not mean that you could ask it what other
>>> types exist which are derived from one of its base types or its exact
>>> type. Sure, D definitely _could_ provide the necessary type information
>>> at runtime (C# and Java do that sort of thing - which is why thy can
>>> have runtime reflection), but it doesn't. At best, you can get
>>> information on the types of a particular object from that object, not
>>> the types which exist in general.
>>>
>>> - Jonathan M Davis
>>
>> So just ignore the bit about dynamic cast completely then and repeat
>> your first incorrect assertion.
>>
>> Yes D and C++ do provide a limited amout of runtime type information.
>>
>> It's called RTTI surprisingly enough. *cough*
>>
>> Dynamic cast, *explicitly* asks at *runtime* if some base class can be
>> converted to a *more derived* class.
>>
>> You *can not* do that unless base classes know about the classes which
>> *inherit from* them.
>
> In current dmd, when you make a cast like: cast (Derived) base, you
> explicitly mentioning the *Derived* type. Its typeinfo contains info
> about classes it derives from, so it the cast just check if type of
> "base" is one of them.

Given two types, you can determine if they are related at compile-time.   
Derived classes contain pointers to their base class' classinfo.

>
> Compiler currently does not push informations from Derived classes to
> base class type info, so it is not possible currently to find out what I
> wanted.

Not at compile time.  The runtime contains all the classinfos, so you can  
iterate them all and find ones that derive from your base.

-Steve


More information about the Digitalmars-d-learn mailing list