Search code examples
c++inheritancediamond-problem

I have a variable b in parent class and when i try to access variable b from sum3 class it shows ambiguous b error


I have a variable b in the parent class and when I try to access variable b from sum3 class it shows an ambiguous b error. And if I remove the sum from inheritance it will give "clas.cpp|25|error: 'int sum::b' is inaccessible within this context| " error what to do?

#include<iostream>
using namespace std;

class sum
{

public:
int b=8;
};

class sum2:sum
{
public:
 int c=4;

};

class sum3:sum2,sum
{
 public:
int h=9;
 void add()
   { 
    int l;
    l=h+c+b;
    cout<<l;
   }
};

int main()
{
  sum3 c;
  c.add();
 }

Solution

  • this is because you are inheriting from both sum2 and sum classes but sum2 is inheriting from sum so it inherits the variable b also so when you intend to use the variable b inside of the class sum3 the compiler doesn't know which variable you want because there is one in class sum2 and one in class sum with the same name b.

    one of the solutions to this is to use the scope resolution operator inside of the class sum3 like this:

        class sum3:sum2,sum
    {
     public:
    int h=9;
     void add()
       { 
        int l;
        l=h+c+sum2::b;
        cout<<l;
       }
    };
    

    this removes the ambiguity by telling the compiler which variable I intend to use and in this case it's sum2 variable.

    Note that:

    this is called the diamond problem and it occurs in multiple inheritance situations if you want to read further and to know how to avoid them you can use this link: How can I avoid the Diamond of Death when using multiple inheritance?