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!