Search code examples
c++inheritancemultiple-inheritancediamond-problem

Question about multi-inheritance in C++?


I have the following code:

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
#define MNAME 30
class Person {
public:
    char name[MNAME + 1];
};
class Student : public Person {
};
class Staff : public Person {
};
class Faculty : public Student, public Staff {
};

int _tmain(int argc, _TCHAR* argv[])
{
    Faculty faculty;
    cout << "Address of faculty.Person::name: " << &faculty.Person::name << endl;
    cout << "Address of faculty.Student::name: " << &faculty.Student::name << endl;
    cout << "Address of faculty.Staff::name: " << &faculty.Staff::name << endl;

    getch();
    return 0;
}

When executed, the program gives the results:

Address of faculty.Person::name: 0012FF20 // **Line 1**
Address of faculty.Student::name: 0012FF20 // **Line 2**
Address of faculty.Staff::name: 0012FF3F // **Line 3**

I don't get it. Why the address in Line 1 and Line 2 is different from Line 3, while both Student and Staff inherits name from Person?


Solution

  • With regular multiple inheritance you get multiple copies of shared base classes. If you want one copy, use virtual inheritance.

    Explained well in Wikipedia

    class Student : public virtual Person {
    };
    class Staff : public virtual Person {
    };
    

    Will get you what you expected