Now what if the parameters for 'a' had nothing to do with the parameters for b?
You need another class to initialise the parameters for A:
class A {
public:
A(int param) { }
};
class InitA {
public:
InitA(int ¶m) { param = complexLogicThatCalculates_As_arg }
};
class B {
public:
B(int param) : InitA(_As_arg), a(_As_arg)
{ whatever initialisation B needs }
private:
int _As_arg;
A a;
};
void setup() {
B b(3);
}
void loop() {}
what if there is an array of As?
No, C++ currently does not support member array initialisation. The following works for primitive types but not user-defined classes. You could probably do it with std::vector but the Arduino compiler library doesn't support the STL AFAIK.
class A {
public:
A(int param) {}
};
class InitA {
public:
InitA(int (¶m)[10]) {
param[0] = ...;
param[1] = ...;
param[2] = ...;
...
}
};
class B {
public:
B(int param) : InitA(arrOfint) {}
private:
int arrOfint[10];
};
void setup() {
B b(3);
}
void loop() {}
or maybe even like this:
class A {
public:
A(int param) {}
};
class InitA {
public:
InitA(int (¶m)[10]) {
param[0] = ...; // Calculate c-tor parameter here
param[1] = ...;
param[2] = ...;
...
}
};
class B {
public:
B(int param) : InitA(arrOfint),
arrOfA[0](arrOfint[0]),
arrOfA[1](arrOfint[1]),
arrOfA[2](arrOfint[2]),
arrOfA[3](arrOfint[3]),
arrOfA[4](arrOfint[4]),
arrOfA[5](arrOfint[5]),
arrOfA[6](arrOfint[6]),
arrOfA[7](arrOfint[7]),
arrOfA[8](arrOfint[8]),
arrOfA[9](arrOfint[9]) { init B}
private:
int arrOfint[10]; // array of As c-tor parameters
A arrOfA[10];
};
void setup() {
B b(3);
}
void loop() {}
or if there is another class "C"
This one's easier, member initialisation is a list, combine with the above methods if required.
class A {
public:
A(int param) {}
};
class InitC {
public:
InitC(int &arg1, int &arg2, int &arg3) {
arg1 = complexLogicThatCalculates_Cs_first_arg;
arg2 = complexLogicThatCalculates_Cs_second_arg;
arg3 = complexLogicThatCalculates_Cs_third_arg;
}
};
class C {
public:
C(int p1, int p2, int p3) {}
};
class B {
public:
B(int param) : a(param), InitC(cp1, cp2, cp3), c(cp1, cp2, cp3) {}
private:
A a;
int cp1, cp2, cp3;
C c;
};
void setup() {
B b(3);
}
void loop() {}
The main gotcha to remember is that the members are initialised in order of declaration in the class, not the order that they appear in the initialisation list.
Search for "C++ member initialization list" or "C++ array member initialization" and you'll get the details of the language syntax required.