C ++ diamond inheritance problems and solutions

1. He inherited a diamond?
Here Insert Picture Description
Two subclasses inherit the same parent class and subclass and there are two sub-classes inherit, they say the figure above shows.

View Code

Problems, will produce ambiguity problem that calls for baseClass scope to explain the situation:

D *pd=new D;

pd->B::a=1;

pd->C::a=2;

printf("%d\n",pd->B::a);

printf("%d\n",pd->C::a);

There are two equivalent baseClass, this may not be the result we want, more difficult to call, but also a waste of memory resources in the class.

This structure is shown:
Here Insert Picture Description
see point A of the position of the virtual function table is not the same, i.e., there are two instances baseClass!!

2. How to solve?

Use virtual inheritance!

View Code

Memory layout:
Here Insert Picture Description
two for baseClass is common, that is, baseClass to instantiate an object Think of what will happen to call B, C when the virtual function on a virtual table how the line, so there is a corresponding need!? virtual table corresponding points B, C, so it becomes the above structure.

! Debugging observed, it is really the case
Here Insert Picture Description
summary: You can remove ambiguity by virtual inheritance, virtual inheritance but the cost is to increase the virtual function pointer.

Published 239 original articles · won praise 3 · Views 3143

Guess you like

Origin blog.csdn.net/it_xiangqiang/article/details/105177007