22.3.3.2.  virtual Base Classes

[ fromfile: multiple-inheritance.xml id: virtualbaseclasses ]

Example 22.9. src/multinheritance/people.h

#include "qdatetime.h"

class Person {
public:
    Person(QString name, QDate birthdate)
    QObject(name.ascii()),
    m_Birthdate(birthdate) {}

    Person(const Person& p) : QObject(p),
    m_Birthdate(p.m_Birthdate) {}

private:
    QDate m_Birthdate;
};

class Student : virtual public Person {       1
    // other class members
};

class Teacher : virtual public Person {       2
    // other class members
}


class GraduateTeachingFellow :
    public Student, public Teacher {          3
public:
    GraduateTeachingFellow(const Person& p,
                           const Student& s, const Teacher& t):
    Person(p), Students(s), Teacher(t) {}     4
}

1

Note keyword virtual here.

2

virtual inheritance.

3

virtual not needed here.

4

It is necessary to initialize all virtual base classes explicitly in multiply-derived classes, to resolve ambiguity about how they should be initialized.


After using virtual inheritance, an instance of GradTeachingFellow might look like Figure 22.6.

Figure 22.6.  GradTeachingFellow - virtual

GradTeachingFellow - virtual