error: cannot convert from pointer to base class ‘Army’ to pointer to derived class ‘ArmyHospital’ because the base is virtual

I ran into this problem of virtual inheritance. I don't know what to do but I tried to reduce the memory. 

 #include <iostream>
using namespace std;

class Army                         // Class declaration
{
private:
    int numberSuffix_;     
    int armyCode_;                
    string name_;
public:
    Army(int armycode, int suffix, string name) : name_(name) {
         //cout << "Parent Class:: " << __func__ << endl;     
    }
   
    string getPatientName() { 
        //cout << "Army " << __func__ << endl;
        return name_; 
    }
};

class ArmyHospital : virtual public Army {
private:
    string hospitalName_;
public:
    ArmyHospital(int armycode, int suffix, string name) : Army(armycode, suffix, name) {
       hospitalName_ = "Kashmir Hospital";
       //cout << "Derived Class: " << __func__ << endl;
    }

    string getPatientName() { 
        //cout << "ArmyHospital  " << __func__ << endl;
        hospitalName_.append(" Officer's name is " + Army::getPatientName());
        return hospitalName_; 
    }
};


int main() 
{
    Army officer(23, 11, "Shirley");
    cout << "The officer's Name is " << officer.getPatientName() << endl << endl;
    ArmyHospital hospy(23, 11, "Sivy");
    cout << "The Hopital's Name is " << hospy.getPatientName() << endl;
    cout << "===========================================" << endl << endl;

    Army* off = new Army(2,1, "Clara");
    cout << "Pointer: The 2nd officer's Name is " << off->getPatientName() << endl << endl;
    ArmyHospital* hos = new ArmyHospital(2, 110, "Rosy");
    cout << "Pointer: The Hospital's Name is " << hos->getPatientName() << endl << endl;
    cout << "===========================================" << endl << endl;


    ArmyHospital* p0 = static_cast<ArmyHospital *>(off); //>>>>>>>>
    return 0;
}

Output:

1
2
3
In function 'int main()':
Line 53: error: cannot convert from base 'Army' to derived type 'ArmyHospital' via virtual base 'Army'
compilation terminated due to -Wfatal-errors.

References :

https://prepinsta.com/c-plus-plus-theory/virtual-base-class/

Comments