Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 967
amod Avatar asked Sep 12 '11 06:09

amod


People also ask

How does it solve the diamond problem?

The solution to the diamond problem is to use the virtual keyword. We make the two parent classes (who inherit from the same grandparent class) into virtual classes in order to avoid two copies of the grandparent class in the child class.

What is Diamond problem and its solution with explanation?

Virtual inheritance solves the classic “Diamond Problem”. It ensures that the child class gets only a single instance of the common base class. In other words, the Snake class will have only one instance of the LivingThing class. The Animal and Reptile classes share this instance.

Does diamond inheritance results in compiler error?

The answer to the titular question is no.

How is Diamond problem solved in C#?

The diamond problem is resolved by the most specific override rule in C# 8. In most specific override rules the class implementation of an interface member always wins.


1 Answers

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.

like image 117
Miguel Avatar answered Nov 08 '22 00:11

Miguel