Search code examples
c++inheritancemultiple-inheritance

Multiple Inheritance in C++ with 3 derived classes


I'm trying to use multiple inheritance. Person is my base class. Student and Angestellter inherit the protected attributes. WissenschaftlicheHilfskraft should also inherit these attributes (from Person, Student, Angestellter), but I can't call the method get_name() in my last derived class. Why?

#include <iostream>

using namespace std;

class Person {
      protected:
              string name;
      public:              //.......
          string get_name() { name = "bob"; return name; }
};

class Student: public Person {
private:    //......
public:     //......
};

class Angestellte: public Person {
private:    //......
public:    //......
};

class WissenschaftlicheHilfskraft : public Student, public Angestellte
{
private: //......
public: //......
};


int main()
{
    Person p;
    cout << p.get_name() << endl;   //WORKS
    Student s;
    cout << s.get_name() << endl;   //WORKS
    Angestellte a;
    cout << a.get_name() << endl;   //WORKS
    WissenschaftlicheHilfskraft wh;
    cout << wh.get_name() << endl;  //DOESN'T WORK
    return 0;
}

I want it to look like this: enter image description here


Solution

  • Also, other than Paul R's answer your inheritance is wrong. You need to use virtual inheritance like as shown here.

    class Student: public Person { becomes class Student: public virtual Person { and so on. This ensures that only one object of base is created for the final object.