mercredi 4 janvier 2017

How to require an object defined by the derived class from within the constructor of a base class

I want to have a generic class that enforces rules for a derived class like in the template method pattern but I would like to avoid two-phase initialization because I don't want objects to be in a partial invalid state if possible. The base class requires a "Thing" which is also a generic class of something that will be used polymorphically. A seperate factory isn't appropriate because I don't yet know what the derived classes will be.

This is what I came up with using function pointers that the derived class passes down during its construction to its base class so it can have the Thing and this way the derived object can never exist without a valid Thing. I wonder if there is a better way to do this because this seems pretty hackish?

class Thing {};

class Base {
public:
    Base(Thing*(*createThing)()): mustHaveThing(createThing()) {};

private:
    Thing* mustHaveThing;
};

class Derived: Base {
public:
    Derived(): Base(createThing) {};

private:
    static Thing* createThing() {
        return new Thing;
    }
};

Aucun commentaire:

Enregistrer un commentaire