Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing class with two members

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?

like image 835
Clinton Avatar asked Jun 21 '26 01:06

Clinton


1 Answers

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)) {}
};
like image 168
ecatmur Avatar answered Jun 23 '26 13:06

ecatmur