Search code examples
c++multiple-inheritancevirtual-inheritance

I need a simple example of when to use non-virtual multiple inheritance


I teach C++, and I need a good, simple, everyday example of when you would use this:

class A {...};
class B : public A {...};
class C : public A {...};
class D : public B, public C {...};

Here D inherits A twice because there is no virtual inheritance involved.

I need an easy-to-understand motivational example of when you might need this construct. I don't even need code for it; I just need to be able to present an example to my students so they exclaim, "Yes, I can see that that would be useful!"


Solution

  • I suggest this example for both virtual and non-virtual multiple inheritance:

    A --> Person (id, name)

    B --> Teacher (salary)

    C --> Student (marks)

    D --> AssitantTeacher

    For me, an AssistantTeacher is a freshly-graduated teacher who is teaching and preparing a higher degree (Masters or PhD). He has a salary as well as marks.

    To add non-virtual flavor, suppose that teachers have ids in a specific format, and students have ids in other format. An AssistantTeacher has two ids: one teacher id (that is used as a primary key in the HR database) and one student id (that is used as a PK in the academic system database).

    [EDIT]

    As an example, the HR ERP system would give an auto-increment id to teachers, and the academic students system would give students ids of the format: YYYYMMSAAAA (where Y is the year of enrollment of the student, M is the month, S is the sex: 0 or 1, and A is an auto-increment id part).

    An AssistantTeacher may have the id "1332" in the HR system and "20170100004" as a student id.