Suppose I want to have a constructor that receives some parameters, and with these parameters I can calculate the values for it's member variables. Except that the values for the member variables are not simple assignments from the parameters. They require creation of other objects and transformation of the values before they can be used as values for the member variables.
This is way to much to cram into an initializer list. Also very inefficient since you can't create variables and reuse them so you will have to copy code (and make several copies of the same object) to fit all the code in the initializer list.
The other option is not to use the initializer list and let the default constructor be called then you overwrite the values inside the constructor with neat calculations.
Now what if the class does not have a default constructor? How can one do this neatly?
/* a class without a default constructor */
struct A {
B x1
B x2
A(B x1_, B x2_) : x1{x1_}, x2{x2_} {}
};
struct C {
A a;
C(D d) : a{/* very complicated */, /* very complicated */} {}
};
Ultimately, I just want to initialize a with two B
objects but unfortunately, they require a lot of work to initialize including instantiating other objects and using tons of methods.
How about adding some static transformation methods?
class C {
private:
static B transform1(D&);
static B transform2(D&);
public:
A a;
C(D d) :
a{transform1(d),transform2(d)}
{}
};
Related: