A base class constructor must be run to initialize the base before you can enter the body of the derived class constructor. The Member Initializer List is the only way to initialize the base class. If you have complex requirements for the parameters, use helper functions to compute the parameters.
Example:
class SuperClass
{
public:
SuperClass(int foo)
{
// do something with foo
}
};
class SubClass : public SuperClass
{
private:
static int basehelper(int foo)
{
// do complicated things to foo
return result_of_complicated_things;
}
public:
SubClass(int foo, int bar)
: SuperClass(basehelper(foo)) // Call the superclass constructor in the subclass' initialization list.
{
// do something with bar
}
};
If the base class parameters require knowledge known only as the derived class is constructed, you must either
- Duplicate the effort,
- Find a way to memoize the results of the helper (perhaps insert a layer of abstraction) and apply the results later in construction,
- Modify the base class to have a simpler constructor and support Two-Phase Initialization, or
- Do something entirely different. Perhaps Composition Over Inheritance is good advice for your use case.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…