Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use only one virtual inheritance in diamond inheritance pattern?

Tags:

c++

Suppose I have some classes: Base, Derived1, Derived2, ...etc. All the derived classes are derived from Base. Now, I want to add some functionality for all derived classes, but these classes can not be modified. So I came up with the following approach:

Create a class Additional using virtual inheritance like this:

class Additional: virtual public Base {
    void f() {
        //some codes operating on class Base
    }
};

Then I can extend each derived class in this way:

class MyDerived1: public Derived1, public Additional {};

However, when I search the Internet, it seems that in diamond inheritance case, we must use virtual inheritance for both classes Derived1 and Additional. As a result, the above approach will not work. So my questions are:

  • Why must we use two virtual inheritance for diamond inheritance case?
  • If my approach does not work, is there another approach that can solve the above difficulty?

Thank you very much!

like image 868
zbh2047 Avatar asked Oct 11 '25 11:10

zbh2047


1 Answers

Why must we use two virtual inheritance for diamond inheritance case?

Virtual inheritance is a contract that a class has to enter into willingly. The class is basically saying that it's willing to share its base sub-object with an instance of another deriving class. It affects object layout and access to the base in the class code. You can't change those things retroactively, especially if the class implementation is compiled and only given to you as an object file.

If my approach does not work, is there another approach that can solve the above difficulty?

Yes, use a template.

template<class BaseT>
class Additional: public BaseT {
    void f() {
        //some codes operating on class Base
    }
};

using MyDerived1 = Additional<Derived1>;
like image 94
StoryTeller - Unslander Monica Avatar answered Oct 14 '25 00:10

StoryTeller - Unslander Monica