Lets say we've got the following:
(1) Class C which has two members X1 x1 and Y1 y1.
(2) C has no default constructor, but does have the constructor C(Z).
(3) A class X1 that has no default constructor, but the constructor X1(X2).
(4) A class Y1 that has no default constructor, but the constructor Y1(Y2).
(5) A function f(Z), which returns std::pair<X2, Y2>
Lets say f(z) -> std::pair<X2, Y2>{x2,y2}.
How do I write the class C such that member X1 x1 == X1(x2) and Y1 y1 == Y1(y2) after construction?
In C++11, you can add a delegating constructor of C:
class C {
X1 x1; Y1 y1;
public:
C(Z z): C(f(Z)) {}
private:
C(std::pair<X2, Y2> p): x1(p.first), x2(p.second) {}
};
If you can't use delegating constructors, the only way to do this is to move the members to helper class B and write C inheriting from B and adding the constructor from Z:
struct B {
X1 x1; Y1 y1;
B(std::pair<X2, Y2> p): x1(p.first), x2(p.second) {}
};
class C: private B {
public:
C(Z z): B(f(Z)) {}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With