How do you return a subclass instance from a base class method?

MorteFeuille123 MorteFeuille123 at mrt.rt
Thu Nov 17 05:21:05 UTC 2022


On Thursday, 17 November 2022 at 04:25:13 UTC, Daniel Donnelly, 
Jr. wrote:
> I have SubclassOf derived from PosetRelation.  For any poset 
> relation, the transitivity law applies, however, I'd like to 
> return the correct type:
>
>
> How does one accomplish this in D?  Because PosetRelation 
> doesn't know about SubclassOf, in general.

You can use TypeInfoClass:

```d
class Base
{
}

class Derived : Base
{
}

Object newDerivedFromTi(Base b)
{
     return typeid(b).create();
}

void main(string[] args)
{
     Base b = new Base;
     Base d = new Derived;
     assert(cast(Derived)newDerivedFromTi(d));
}
```

But that only works with default constructors, i.e no parameters.
Another way is to define a virtual function in the Base:

```d
class Base
{
     Object createMostDerived(Base b1, Base b2)
     {
         return new typeof(this);
     }
}

class Derived : Base
{
     override Object createMostDerived(Base b1, Base b2)
     {
         return new typeof(this);
     }
}

Object newDerivedFromTi(Base b)
{
     return b.createMostDerived(b, b);
}

void main(string[] args)
{
     Base b = new Base;
     Base d = new Derived;
     assert(cast(Derived)newDerivedFromTi(d));
}
```

assuming the PosetRelation (here called Base) actually cary the 
SubclassOf type (here called Derived).


More information about the Digitalmars-d-learn mailing list