ddeflyer
ddeflyer

Reputation: 96

Class factory mixin

I would like to create in a mixin class that would impart a class factory method for the final class of a concrete type through several layers of inheritance. More specifically, I would like to have the factory method produce a new instance of the actual object it is called as a member of.

So, class "factory" is inherited by class A, class A is inherited by class B, I would like to find a way to do B::create() and create an instance of B. As far as I can tell this precludes the use of a template taking the type in the class A since then B::create() would produce an instance of A.

Upvotes: 3

Views: 265

Answers (2)

n. m. could be an AI
n. m. could be an AI

Reputation: 119877

You can't. The code in the base class knows nothing about any of the derived classes, unless you specifically inject this kind of knowledge yourself, by means of a template parameter or otherwise. There's no way to do that automatically.

Upvotes: 1

vines
vines

Reputation: 5225

Maybe CRTP would do? http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

template <typename T>
struct Mixin
{
    T * create() const { return new T; }
};

class Target : public Mixin<Target>
{
    ...
};

Upvotes: 2

Related Questions