-1

with the following code

class A {
    int b;
    int c;
};

class B : virtual A {
    //constructor initialize b and c to something
};

class C : virtual A {
    //constructor initialize b and c to something else
};

class D : public C, public D {
};

how can D have b initialize by B and the c initialize by C ?

P.S. : i am learning about diamond inheritance, this as not functional purpose, i just wanna know if its possible

edit : human father mother and child where confusing so i renamed everything to ABCD. also fixe some code error and add clarification

  • 2
    Child has eyes and nose of a Human. – Eljay Sep 28 '22 at 12:15
  • You can assign the **value** for `eyes` of a child to that of his mother, and the **value** for `nose` from that of his father. The members themselves exist in the `Child` because they are inherited from `Human` as mentioned in the comment above. – wohlstad Sep 28 '22 at 12:17
  • 1
    the question is somewhat unclear. With virtual inheritance `Child` must call the `Human` cosntructor, hence it is not clear what you mean with "eyes of the father". Imho the `child` - `father` / `mother` is not the best mental model for (virtual) inheritance, don't expect the analogy to make too much sense – 463035818_is_not_an_ai Sep 28 '22 at 12:22
  • 1
    See [this answer](https://stackoverflow.com/a/2659142/4641116) which explains how `virtual` inheritance fixes the diamond inheritance problem. (Sometime the "problem" is a problem, sometimes it's the right thing; depends on the design and what is trying to be implemented.) – Eljay Sep 28 '22 at 12:23
  • taken the question literally: `Child` has neither his fathers nose nor his mothers eyes, it has `Human`s nose and eyes. Thats virtual inheritance in a nutshell ;) – 463035818_is_not_an_ai Sep 28 '22 at 12:24
  • 1
    In object oriented design not everything needs to be solved by inheritance!! Composition is just as valuable. You can create a child by recomposing parts of the father and mother, so a father has a nose and a mother has a nose, and a child has a nose. Take it from there. IMO : In general just avoid diamond inheritance. Inherit from interfaces if you must and use composition again to do code reuse. – Pepijn Kramer Sep 28 '22 at 12:25
  • to clarify, i want the nose to be the same initialize by the father, and the eyes to be the same initialize by the mother. also maybe composition is better in this case, but its an exercise about diamond inheritance – elgecko rien Sep 28 '22 at 12:33

1 Answers1

0

how can D have b initialize by B and the c initialize by C ?

With virtual inheritance the most derived class must initialize the virtual base. Not B or C construct Ds subobject of type A, but D does that.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185