bolov
bolov

Reputation: 75727

Scope operator for base class in super multiple non-virtual inheritance

Consider this (completely non-nonsensical, but perfectly valid) class inheritance:

struct Area { int size; };
struct Pattern { int size; };

struct R : Area, Pattern {};
struct C : Area, Pattern {};

struct X: R , C {};

Let's see a graph of this great hierarchy:

Area  Pattern
  |\  /|   
  | \/ |
  | /\ |  
  |/  \|
  R    C
   \  /
    \/
    X

Now, if I am not mistaken, X should have 4 size members.

How to refer to them using the scope operator?

The obvious solution doesn't work:

X x;
x.R::Area::size = 24;

clang error:

23 : <source>:23:3: error: ambiguous conversion from derived class 'X' to base class 'Area':
    struct X -> struct R -> struct Area
    struct X -> struct C -> struct Area
  x.R::Area::size = 8;
  ^
1 error generated.

gcc error:

<source>: In function 'auto test()':
23 : <source>:23:14: error: 'Area' is an ambiguous base of 'X'
   x.R::Area::size = 8;
              ^~~~

Some much needed clarification:

Upvotes: 5

Views: 169

Answers (1)

Massimiliano Janes
Massimiliano Janes

Reputation: 5624

something like static_cast<R&>(x).Area::size = 8;

which is as ugly as it should be :)

To clarify why the original code doesn't work, it's worth mentioning that a qualified id has the form (among others) type-name::id so x.R::Area::y is equivalent to using T = R::Area; x.T::y; that clearly does not help as far as disambiguation is concerned.

Upvotes: 5

Related Questions