The main problem with multiple inheritance is that there can be times
when the results of using multiple inheritance will be uncertain. The
best example of this is the classic problem known as the Diamond Problem where a class inherits from 2 different classes, but those 2 different
classes inherit from the same class, like in the graphic below (where
class D derives from both classes B and C, and classes B and C both
derive from class A:
And here is what the code for that example would look like:
In the code above we have the testing data member which is defined by class A. But, the problem is that class D derives from both classes B and C, which both derive from class A. This means that there are essentially 2 copies of the testing flag that are available because there are 2 instances of A in D’s class hierarchy. So, this creates a problem because which copy of the testing flag will be set? And the compiler will give an error and say that the reference to testing in class D is ambiguous.
But, there are some fixes to this problem. One fix is to make it very clear which classe’s version of testing is going to be set:
The other fix for this problem is to declare B and C as virtual base classes. This allows only one copy of A to be created for class D, and that clears up any ambiguities.
And here is what the code for that example would look like:
class A { protected: bool testing; }; class B: public A { }; class C: public A { }; class D: public B, public C { public: void setTesting ( bool xTesting) { testing = xTesting; // this is uncertain } };
In the code above we have the testing data member which is defined by class A. But, the problem is that class D derives from both classes B and C, which both derive from class A. This means that there are essentially 2 copies of the testing flag that are available because there are 2 instances of A in D’s class hierarchy. So, this creates a problem because which copy of the testing flag will be set? And the compiler will give an error and say that the reference to testing in class D is ambiguous.
But, there are some fixes to this problem. One fix is to make it very clear which classe’s version of testing is going to be set:
B :: testing = xTesting; // use B's version of testing
The other fix for this problem is to declare B and C as virtual base classes. This allows only one copy of A to be created for class D, and that clears up any ambiguities.
No comments:
Post a Comment