Pregunta

Ok so I understand how to solve the problem of the diamond of death inheritance when you have full control over all the classes but what if you only have control over the last class to inherit from both So I have this:

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

and I have no way of editing B and C only D, is there an easy way I can do this?

¿Fue útil?

Solución 2

Fake it by containment. Have D contain B and C and give D the same public interface as the union of B and C's public interface. Then call the appropriate methods of B and C from D's public interface.

Of course you will have a problem casting and polymorphism as it won't follow the laws of inheritance.

In short, there's no good way.

Otros consejos

The is a very good reason you can't force B and C to share A. Consider:

struct A {int i;};
struct B : A {
 B(){i=3;}
 void foo() {
  //crash if i!=3
 }
};
struct C : A {
 C(){i=4;}
 void bar() {
  //crash if i!=4
 }
};

B and C are good classes. They can't handle a situation that they won't get in (invalid value of i).

If there was a way to do what you ask for (struct D:B,C, where B and C share A), what will be the value of D::A::i?

virtual inheritance means "I need this class, but I won't require some valid values for it, and I completely fine with somebody else mess with it".

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top