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:
Thank you very much!
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>;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With