Diamond inheritance with shared attribute in C++

119 Views Asked by At

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

1

There are 1 best solutions below

0
463035818_is_not_an_ai On

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.