c++ - Proper way to make base class setup parent class -
i'm struggling bit following situation: lets have class "base" requires information in order work properly. therefore, i've set single constructor appropriate parameters, e.g.:
class base { public: base(x x, y y, z z); }; this works fine general "bases". i'd have subclasses represent specific "bases" used , contain information required setup base class, e.g.:
class derived { public: derived() { x x; x.addsomeinformation("foo bar"); // ... // what? } }; problem here cannot invoke parent constructor via initializer list (as 1 do) becaues parameters handed on not yet exist.
due this, feel wrong design. can make work introducing protected default constructor , "configure" method imitates normal constructor, i'm not sure if idea (mainly because way cannot ensure subclass invokes "configure" - , if doesn't leave me not initialized base class):
class base { public: base(x x, y y, z z) { configure(x, y, z); } protected: base() {} protected: void configure(x x, y y, z z); }; class derived { public: derived() { x x; // ... configure(x, y, z); } }; how 1 deal such situation in proper way?
my first suggestion make x have valuable constructor rather forcing default-constructed:
class derived { public: derived() : base(x("foo bar"), <blah>) { } }; if that's not option, split x-creation logic function , use that:
class derived { public: derived() : base(make_x(), <blah>) { } private: static x make_x() { x x; x.addsomeinformation("foo bar"); // else needed. return x; } };
Comments
Post a Comment