Suppose I have a class
class Widget
{
public:
explicit Widget();
explicit Widget(int foo, int bar);
private:
Gadget * gadget_;
int foo_{42};
int bar_{13};
}
with constructors that use some members (therefore initialization order is important):
Widget::Widget()
{
ComplicatedConstructionStandIn::frobnicate_gadget(&gadget_);
TheConstructorHasManyLines(foo_, gadget_);
ItDoesMultipleThings(bar_);
}
Widget::Widget(int foo, int bar)
: foo_{foo}
, bar_{bar}
{
ComplicatedConstructionStandIn::frobnicate_gadget(&gadget_);
TheConstructorHasManyLines(foo_, gadget_);
ItDoesMultipleThings(bar_);
}
Clearly, the second constructor is code duplication so you would think to delegate !BUT! you can't do that if you also want the default member initialization (int foo{42};
).
By delegation I mean something like this (does not compile):
Widget::Widget(int foo, int bar)
: foo_{foo}
, bar_{bar}
, Widget()
{}
Is there an elegant way out of this? Wrapping the body of the constructor in an auxiliary init function is just kicking the question down the line.