I have written a simple program that deals with repeated inheritance. I use a base class, two child classes and a grandchild class
class Parent{
public:
Parent(string Word = "", double A = 1.00, double B = 1.00): sWord(Word), dA(A), dB(B){
}
//Member function
void Operation(){
cout << dA << " + " << dB << " = " << (dA + dB) << endl;
}
protected:
string sWord;
double dA;
double dB;
};
Now here is the first child class
class Child1 : public Parent{
public:
//Constructor with initialisation list and inherited data values from Parent class
Child1(string Word, double A, double B , string Text = "" , double C = 0.00, double D = 0.00): Parent(Word, A, B), sText(Text), dC(C), dD(D){};
//member function
void Operation(){
cout << dA << " x " << dB << " x " << dC << " x " << dD << " = " << (dA*dB*dC*dD) << endl;}
void Average(){
cout << "Average: " << ((dA+dB+dC+dD)/4) << endl;}
protected:
string sText;
double dC;
double dD;
};
Here is the second child class
class Child2 : public Parent {
public:
//Constructor with explicit inherited initialisation list and inherited data values from Base Class
Child2(string Word, double A, double B, string Name = "", double E = 0.00, double F = 0.00): Parent(Word, A, B), sName(Name), dE(E), dF(F){}
//member functions
void Operation(){
cout << "( " << dA << " x " << dB << " ) - ( " << dE << " / " << dF << " )" << " = "
<< (dA*dB)-(dE/dF) << endl;}
void Average(){
cout << "Average: " << ((dA+dB+dE+dF)/4) << endl;}
protected:
string sName;
double dE;
double dF;
};
Here is the grandchild class that deals with multiple inheritance
class GrandChild : public Child1, public Child2{
public:
//Constructor with explicitly inherited data members
GrandChild(string Text, double C, double D,
string Name, double E, double F): Child1(Text, C, D), Child2(Name, E, F){}
//member function
void Operation(){
cout << "Sum: " << (dC + dD + dE + dF) << endl;
}
};
In the main function I then create a GrandChild object and initialise it like so:
GrandChild gObj("N\A", 24, 7, "N\A", 19, 6);
//calling the void data member function in the GrandChild class
gObj.Operation();
The answer I get to this is
SUM: 0
However the answer should be 56! Clearly the default inherited values used in the constructor for the GrandChild class are being used, and not the data values that are included in the construction of the GrandChild object. How can I solve this problem?