开发者

How does the compiler internally solve the diamond problem in C++?

We kn开发者_Go百科ow that we can solve the diamond problem using virtual inheritance.

For example:

   class Animal // base class
   {
     int weight;
     public:
     int getWeight() { return weight;};
   };
   class Tiger : public Animal { /* ... */ }; 
   class Lion : public Animal { /* ... */ };
   class Liger : public Tiger, public Lion { /* ... */ }; 
   int main()
   {
     Liger lg ;
     /*COMPILE ERROR, the code below will not get past
     any C++ compiler */
     int weight = lg.getWeight();
   }

When we compile this code we will get an ambiguity error. Now my question is how compiler internally detects this ambiguity problem (diamond problem).


The compiler builds tables that list all the members of every class, and also has links that allow it to go up and down the inheritance chain for any class.

When it needs to locate a member variable (weight in your example) the compiler starts from the actual class, in your case Liger. It won't find a weight member there, so it then moves one level up to the parent class(es). In this case there are two, so it scans both Tiger and Lion for a member of name weight. There aren't still any hits, so now it needs to go up one more level, but it needs to do it twice, once for each class at this level. This continues until the required member is found at some level of the inheritance tree. If at any given level it finds only one member considering all the multiple inheritance branches everything is good, if it finds two or more members with the required name then it cannot decide which one to pick so it errors.


When compiler creates a table of function pointers for a class, every symbol must appear in it exactly once. In this example, getWeight appears twice: in Tiger and in Lion (because Liger doesn't implement it, so it goes up the tree to look for it), thus the compiler gets stuck.

It's pretty simple, actually.


With your code, the structure for liger is

Liger[Tiger[Animal]Lion[Animal]]

If you call an Animal function from a Liger pointer, there are actually two Animal a Liger can convert to (hence the ambiguity)

Virtual inheritance will generate a structure like

Liger[Tiger[*]Lion[Animal]]
            \-----/

There is now just one Animal, indirectly reachable from both of the bases, so a conversion from Liger to Animal is anymore ambiguous.


the compiler does not detect the ambiguity problem. the compiler is only interested in the declarations of what is being used in the code. the compiler does not complain if an element is declared more than once.

the ambiguity problem comes from the linker. the linker sees two definitions of the getWeight() function within the inheritance tree of the object lg, and does not know which definition to choose to link with the call lg.getWeight(). so that's the ambiguity.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜