Value of member variable in multiple inheritance | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Value of member variable in multiple inheritance

Hi Please refer class D which is inherited from B and C As D's constructor gets called last post all base classes, 3 is expected to get for a in case D has constructor Question is about value of a if D constructor is commented I was expecting output 2 but it prints 0..why? B constructor sets a as 1 and then c should set to 2 but why output is 0? If D has been inherited like D : public C, public B Output should be 1.? Is this correct ? https://code.sololearn.com/cKkgvSg6agzo/?ref=app

9th Apr 2022, 1:25 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
6 Answers
9th Apr 2022, 1:44 PM
William Owens
William Owens - avatar
0
Yeah I am aware about diamond problem and virtual inheritance.. My concern is about constructor calls.... If object d is not calling constructors if B and C, isn't it a bad thing ? What if these two classes manages resources via constructor
9th Apr 2022, 2:48 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
I have different perspective to look at this as below : C is derived from A and hence variable a of A is accessible to C. Variable is still in A and just available to C object as well due to inheritance Now as soon as C constructor gets called , variable of struct A is assigned to 2... I hope inheritance of D from C forces D' default constructor to call C's default constructor which should set value of a to 2 I feel that value should be 2. Is it not true ?
9th Apr 2022, 4:47 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Also if I just remove virtual from struct c declaration and D just gets inherited from C alone, I got 2 as output as expected without D constructor uncommented Does this means due to virtual inheritance, C and B constructors don't get called ? Dimaond problem forced us to use virtual inheritance but it is having flaw of not calling inheritance heircrchy constructors Isn't it ?
9th Apr 2022, 4:50 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Basic question : why constructor not called for struct C even though D obj is created Rest all are the work around and not much interested... Also value of a is not main concern for me. I just want to understand that c constructor should get caled or bit for object of D ?
9th Apr 2022, 8:57 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
I just updated a line into c struct constructor... It seems c constructor getting called and prints hi as well Now another question: why a is not modified and prints value 0?
9th Apr 2022, 8:59 PM
Ketan Lalcheta
Ketan Lalcheta - avatar