How to deal with diamond inheritance in C++
This article introduces the relevant knowledge of "how to deal with diamond inheritance in C++". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Encapsulation, inheritance, polymorphism. These are the three major features of C++ language, and every time we talk about inheritance, we inevitably talk about a very important issue, diamond inheritance.
The derived class inherits the parent class, as well as all member copies in the parent class, but if a base class is inherited by two subclasses at the same time, and then a new class is derived from the above two subclasses. To some extent, this forms the diamond inheritance in C++, which can also be called diamond inheritance, as shown in the following figure:
The class diagram above says that Left and Right derive the child Top, respectively, but Bottom inherits Left and Right, respectively. Inheritance relationships can also be drawn in the following way, so that you can better understand the problems in the design.
This class diagram clearly shows the shortcomings in class design. When trying to convert a pointer to a Bottom object to a pointer to Top, there are two Top objects to choose from, but the compiler is obviously not so smart, which leads to ambiguity in the conversion process. Similarly, Bottom objects cannot directly call methods defined in Top. If you want to use them, you need to provide a top sub-object, but you can see from the class diagram that there are two Top objects.
The code for the above class is:
Class Top {public: int _ x: public: Top (int x): _ x (x) {}; class Left:public Top {public: int _ y: Left (int x paper int y): Top (x), _ y (y) {}; class Right:public Top {public: int _ z: public: Right (int x): Top (x), _ z (z) {}; class Bottom:public Left,public Right {public: int _ w Public: Bottom (int xreint yreint zpenint w): Left (xjingz), Right (ypencil z), _ w (w) {};}
The following implementation of the test program for this class is as follows:
Int main () {Bottom bf (1, 2, 3, 4); cout