C + + allows multiple inheritance, and multiple inheritance is a place where C + + differs from some other popular languages. For example, in Java there is no multiple inheritance, for this, when it comes to similar C + + multiple inheritance scenarios, Java and other languages use the form of "interface" to achieve the purpose, in C + + is not the concept of interface, the use of corresponding requirements of the virtual base class to implement multiple inheritance. Here's a look at the basic usage of multiple inheritance and a few caveats.
class base{public: int baseint;};
- Two parallel classes that inherit from the base class
Public base{Left (): Base () // Note to inherit the base class constructor { }};
Public base{Right (): Base () // Note to inherit the base class constructor { }};
- Multiple inheritance of the above two classes
Public Public right{ Multi (): Base (), left (), right () // inherit all base class constructors { }};
"Attention"The logical structure of the above multiple inheritance methods is as follows: There will be duplicate base member Baseint in multi, and when used to this variable will produce ambiguity without compiling the workaround: When left and right inherit base, use virtual inheritance (This virtual and virtual function has no relation), similar to the following: Clase Left: Virtual PublicBase "Attention"When using left* left to point to a multi object, if you want to use a variable or function that inherits from right, we will need to convert the pointer of that right type to a right pointer, at this point: right* right = (right*) to leave; Error right* right = dynamic_cast<right*> (left); Correct, because left and right are in a peer relationship in the inheritance mechanism, the conversion also becomes a cross-conversion reason:because of the various virtual functions inherited, the multi object will maintain a vtable for each of the directly inherited base classes (This section searches for these keywords to understand: Virtual functions, dynamic bindings, run-time polymorphism), according to the sequential sequence of inheritance, Vtable the address of the function inherited from the corresponding base class, and the direct cast will result in error checking vtable
Multiple inheritance for C + +