c++ - How to require an object defined by the derived class from within the constructor of a base class -
i want have generic class enforces rules derived class in template method pattern avoid two-phase initialization because don't want objects in partial invalid state if possible. base class requires "thing" generic class of used polymorphically. seperate factory isn't appropriate because don't yet know derived classes be.
this came using function pointers derived class passes down during construction base class can have thing , way derived object can never exist without valid thing. wonder if there better way in c++ because seems pretty hackish?
edit: corrected bit better syntax without function pointers. think simplest way this.
class thing {}; class base { public: base(thing* thing): musthavething(thing) {}; virtual ~base() { delete musthavething; }; private: thing* musthavething; }; class derived: base { public: derived(): base(creatething()) {}; private: static thing* creatething() { return new thing; } };
Comments
Post a Comment