One of the problems that multiple inheritance can easily bring is ambiguity:
1 classborrowable{2 Public:3 voidCheckOut ()Const;4 ...5 };6 classelectronicgadget{7 Private:8 BOOLCheckOut ()Const;9 ...Ten }; One classMp3player: A PublicBorrowableitem, - PublicElectronicgadget - {...}; the Mp3player MP; -Mp.checkout ();
This checkout call is actually undefined, regardless of the scope, the MP can get two checkout names. The possible method of invocation is: MP. Borrowableitem::checkout (); Another fatal problem is that if the two base classes also have the same base class, it causes the base object to recur. The correct approach is to use virtual inheritance as follows, which avoids inheriting the same data:
1 class file{...}; 2 virtual public file{...}; 3 virtual public file{...}; 4 public Inputfile, 5 OutputFile 6 {...};
Of course, using virtual inheritance is a cost, and the resulting objects tend to be larger and the access speed slows. Another less significant drawback is that the final class obtained through virtual inheritance often has more than one inheritance distance from the base class that contains the data. But these classes are also responsible for these Buddhas, such as the initialization of the work. So in summary: the advice for virtual base class is very simple: do not have to use virtual base, if you want to use to try not to store data in virtual base, so as not to forget the initialization of the work to bring some strange consequences. Summary: Multiple inheritance is more complex than a single inheritance, may lead to new ambiguity, and often requires virtual inheritance of virtual inheritance will increase, size, speed, initialization, complexity and other costs, the best virtual base class should not have data. The correct use of multiple inheritance often occurs when pubic inherits from the combination of a interface class and a class that assists in the implementation of the private inheritance word.
Article 40: Careful selection of multiple inheritance