Search code examples
c++virtualmultiple-inheritancediamond-problem

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


We know 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).


Solution

  • 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.