Syntactic Sugar for Virtual Constructors?

Christopher Wright dhasenan at gmail.com
Thu Feb 28 18:11:17 PST 2008


Janice Caron wrote:
> On 28/02/2008, Robert Fraser <fraserofthenight at gmail.com> wrote:
>> Why not just return the instance of MyClass? More flexible, since it
>>  doesn't need to have a default constructor in the general case:
> 
> No, that would be /less/ flexible, since the factory function would
> have to know about every possible derived class at compile time. The
> whole point of a generic factory function is that it has no
> compile-time knowledge of the derived classes. /All/ information about
> derived classes is delayed until runtime.
> 
> The only practical way to do that is to call Object.factory(), and
> since Object.factory() takes a string parameter, a string is what the
> function needs to supply.

So, generate these strings at runtime? The solution:
AbstractBaseClass delegate () [string] builders;

class Derived : AbstractBaseClass
{
    static this ()
    {
       builders["whatever"] = { return new Derived1(); };
    }
}


Of course, you're just talking about syntactic sugar. In this case, I'm 
quite opposed, since it violates the typical expectation that typeof 
(new T) == T.



More information about the Digitalmars-d mailing list