0

Lets suppose situation.

struct Top
{
  int x;
};

struct Left : public Top
{};

struct Right : public Top
{};

struct Bottom : public Left, public Right
{
  void foo()
  {
    Left::x; // Normal compiled
  }

  void goo()
  {
    Left::Top::x; // error: ‘Top’ is an ambiguous base of ‘Bottom’ // Why --- ????
  }
};

Could someone explain me why in function goo() compiler give ambiguity error?

I wrote void foo() to show that if i access x by qualifier Left::x; there is no ambiguity, so why when i use more detailed access qualifier Left::Top::x; ambiguity appears?

  • By the way i tried this code in visual studio 2012( default compiler settings ) and it compiled. But gcc - 4.6 ( ubuntu ) gives that error. So as i understand it is gcc - 4.6 problem, or??? I don't know, if somebody know something about it please write the answer. – Vahagn Babajanyan Mar 04 '13 at 14:12

1 Answers1

0

Your problem is known as "Diamond problem" in OOP languages. Remember that :: just guides where to find something, not how to explicitly take that one. In method foo, your refering to the x, which is known by left. That's ohkay so far. But in method goo, your saying "get the x >which is known by Top<, which is known by Left". But this reference doesn't change the fact, that your class Right also knows a class Top. So in your case, Left::Top::x is the same as writing Top::x. And the result is, it's ambiguous, which Top's x you want, the one inheritaed by Left, or the one of Right. Of course in your case, its just a single type where the compiler couldn't run in much troubble. But it's a generell rule, and such stuff could get quickly pretty weird ;)

dhein
  • 6,431
  • 4
  • 42
  • 74