Re: ambiguity in diamond inheritance
On 2008-03-06 23:34:45 -0500, karthikbalaguru
<karthikbalaguru79@gmail.com> said:
I understand the Diamond Problem and the solution of "Virtual
Inheritance"
that is used to overcome ambiguity.
But, i wonder why should the Diamond problem arise. This should
be taken care by C++ internally and resolved. Why C++ could not
handle it internally without asking us to do the 'virtual
inheritance'?
"The Diamond Problem" arises because the writer of a class hierarchy
didn't understand how inheritance works.
struct A
{
int i;
};
struct B : A
{
};
struct C : A
{
};
struct D : B, C
{
void f();
};
void D::f()
{
i = 3; // error: ambiguous
}
There are two separate "i" members in D. There's no way the compiler
can "handle it internally". You have to say what you mean:
void D::f()
{
B::i = 3; // OK: B's "i" member
}
If you don't want to have two "I" members in D, then the inheritance
hierarchy as written above is wrong. If the design calls for only one A
subobject, you do that by making A a virtual base everywhere. Then
there's only one "i" member in D. But note that that's a design
decision, not an implementation decision. Either you have only one A
subobject, in which case "i" is unambibuous, or you have two, and you
have to say which one you mean.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)