Virtual inheritance
This is a multi-part message in MIME format.
------=_NextPart_000_0040_01C78ADB.2F1CB570
Content-Type: text/plain;
format=flowed;
charset="iso-8859-1";
reply-type=original
Content-Transfer-Encoding: 7bit
Hi to all, I'm facing a problem in a particularly complex inheritance
hierarchy, and I'd like to know what the standard says about it and if my
compiler is correct in what it does.
I have two consecutive layers of diamond-shaped inheritance; the first layer
is declared as using virtual inheritance, while the second one is declared
as *not* using it.
This is what I'd like to have:
Base Base
/ \ / \
D1Base D2Base D1Base D2Base
\ / \ /
Middle Middle
|| ||
D1Middle D2Middle
\ /
\ /
\ /
Last
This is what the compiler actually does:
Base
/ D1Base D2Base
\ /
Middle
/ D1Middle D2Middle
\ /
Last
If I remove all virtual inheritance, everything goes just fine; if I use it
in the first layer, there seems to be no way of disabling it afterwards.
Does the standard saying anything about this, or is it
implementation-dependant? My compiler is Visual Studio 2005.
Code sample attached.
Thanks
Massimo
------=_NextPart_000_0040_01C78ADB.2F1CB570
Content-Type: text/plain;
format=flowed;
name="Prova.cpp";
reply-type=original
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment;
filename="Prova.cpp"
#include <iostream>
using namespace std;
class Base
{
private:
int n;
public:
void SetN(int n)
{
this->n = n;
}
int GetN(void)
{
return(n);
}
};
class D1Base:
public virtual Base
{};
class D2Base:
public virtual Base
{};
class Middle:
public D1Base,
public D2Base
{
// I want Middle to only have one copy of n;
// This goes ok.
};
class D1Middle:
public Middle
{
// I want D1Middle to have its own Middle object
// and its own n.
};
class D2Middle:
public Middle
{
// I want D2Middle to have its own Middle object
// and its own n.
};
class Last:
public D1Middle,
public D2Middle
{
// I want Last to access two different Middle objects
// and, ultimately, two different n's.
// This doesn't happen.
};
int main(int,char**)
{
Last* l = new Last;
l->D1Middle::SetN(42);
l->D2Middle::SetN(43);
cout << l->D1Middle::GetN() << endl;
cout << l->D2Middle::GetN() << endl;
cin.get();
return(0);
}
------=_NextPart_000_0040_01C78ADB.2F1CB570--