Suppose I have a base class B, and a derived class D. I wish to have a method foo() within my base class that returns a new object of whatever type the instance is. So, for example, if I call B.foo() it returns an object of type B, while if I call D.foo() it returns an object of type D; meanwhile, the implementation resides solely in the base class B.
Is this possible?
Don’t. Make the ‘foo’ method abstract.
Or receive an abstract factory through the base class constructor:
Add covariant return types and generics to taste.