-2
Please have a look at the code:
#include <iostream>
using namespace std;

 class base1
 {
 public:
    int x,y;
 };
  class base2
 {
 public:
    int x, z;
 };

 class derived: virtual public  base1,virtual public  base2
 {
    public:
     void display(int a, int b, int c)
     {
        x=a;
        y=b;
        z=c;
        cout<<x<<endl<<y<<endl<<z<,endl;

     }
 };

 int main()
 {
    derived dr;
    dr.display(1,2,3);
 }

As the base classes base1 and base2 are made virtual, it should solve the issue of declaration of x in these classes. But, it is not. It is giving me an error: error: reference to ‘x’ is ambiguous Can anyone please put light?

Krish Munot
  • 1,093
  • 2
  • 18
  • 29
coder999
  • 15
  • 7

2 Answers2

1

This is not a diamond inheritance issue. You have:

base1  base2
 ^      ^
 |      |
 \      /
  \    /
   \  /
    \/
 derived

The problem is that both base1 and base2 have member x.

You need to disambiguate x from derived using base1:: or base2:: even though you don't have a diamond inheritance.

Ignoring for the time being the rationale for changing the values of member variables in derived::display, you can use:

class derived: virtual public  base1,virtual public  base2
{
   public:
      void display(int a, int b, int c)
      {
         base1::x=a;
         y=b;
         z=c;
         cout<<base1::x<<endl<<y<<endl<<z<<endl;
      }
};
R Sahu
  • 204,454
  • 14
  • 159
  • 270
-1

Instead of referencing to vague x, y, and z variables, use base1.x or base2.x. For example:

CHANGE

    x=a;
    y=b;
    z=c;
    cout<<x<<endl<<y<<endl<<z<<endl;

TO

    base1 b1;
    base2 b2;
    b1.x=a;
    b2.x=a;
    b1.y=b;
    b2.z=c;
    cout<<b2.x<<endl<<b1.y<<endl<<b2.z<,endl;

OR TO: (if you wanted to change the this values)

    base1::x=a;
    base2::x=a;
    base1::y=b;
    base2::z=c;
    cout<<base2::x<<endl<<base1::y<<endl<<base2::z<,endl;
Vaibhav Bajaj
  • 1,934
  • 16
  • 29