4
struct B { int i; };
struct D1 : virtual B {};
struct D2 : B {};  // <-- not virtual
struct DD : D1, D2 {};

Having coded above, still the compiler demands D2 also to be virtual:

DD d;
d.i = 0; // error: request for member `i' is ambiguous

What I don't understand is, once you have prompted compiler that B is virtual with respect to DD (via D1) then why it still i is ambiguous ?

(If my memory serves correct, the older VC++ (in 2006), was capable enough to make out this just with single virtual inheritance)

iammilind
  • 68,093
  • 33
  • 169
  • 336

3 Answers3

7

B is not virtual with respect to DD - it is virtual with respect to D1. At the time D2 is created, it contains a full copy of B. So now DD has two implementations of B: one as part of D2, and one at the end (pointed by D1). And having two copies of i, using it is indeed ambiguous.

Had D2 also used virtual inheritance, instead of containing a copy of B, it would have contained a pointer to the instance of B that D1 is also pointing at, and DD would have contained only one instance of B.

I'll try to illustrate the memory layouts, hope this comes out right...:

Your case, with one virtual inheritance and one non-virtual -

|    D1    |   D2 + B |    B    |
+--+-------+----------+---------+
 |   vptr to B           ^
 +-----------------------|

Having both D1 and D2 inherit virtually -

|   D1   |   D2   |   B   |
+--+-----+---+----+-------+
 |         |         ^
 +---------+---------|
Eran
  • 21,632
  • 6
  • 56
  • 89
2

You must read Diamond problem . Under the Approaches heading, for CPP, your case is clearly mentioned, your observation matches the one explained there.

Gurpreet Singh
  • 1,326
  • 3
  • 15
  • 21
  • That's a good link, but as you said; it shows the observation. I wanted to know **reason** behind it. What happens under the hood (in brief). – iammilind Jul 08 '11 at 06:20
  • I think the article about [Virtual Inheritance](http://en.wikipedia.org/wiki/Virtual_inheritance) could be more instrumental for a deeper understanding of what happens under the hood. – Eran Jul 08 '11 at 08:02
  • Wikipedia links are not answers. – cHao Jul 27 '12 at 12:52
2

The standard requires that d.i must be ambiguous in this case. ISO/IEC 14882:2003 section 10.1.6 covers classes with virtual and non-virtual base classes of a given type.

David Hammen
  • 32,454
  • 9
  • 60
  • 108