typeof(this) and subclasses

kris foo at bar.com
Sat Aug 12 14:11:39 PDT 2006


Serg Kovrov wrote:
> Hello D-people =)
> 
> Is there a way to get type of subclass in method defined in superclass, 
> but called in subclass?
> 
> Here a class hierarchy:
> 
>> class Foo
>> {
>>   static typeof(this) create()
>>   {
>>     // ... some init code
>>     return new typeof(this)(init);
>>   }
>> }
>>
>> class FooBar : Foo
>> {
>>   /* FooBar doesn't overriding create() */
>> }
> 
> 
> and I'd like to create them as follows:
> 
>> auto f = Foo.create();    // f is instance of Foo
>> auto b = FooBar.create(); // b should be instance of FooBar
> 
> 
> But, because of 'typeof(this)' appears to be evaluated where it defined 
> instead of where it called (sorry for possible misuse of terminology, 
> but I hope you got my idea), 'b' is type of 'Foo' instead of desired 
> 'FooBar'.
> 

I suspect the "typeof(this)" is evaluated statically, at compile time. 
You might as well write "Foo" instead?



More information about the Digitalmars-d-learn mailing list