Reputation: 3257
I have a code shown below. XBase
and XBar
are classes of X
library, so I'm not able to change them.
#include <iostream>
using namespace std;
// -- library stuff -- I can't change this
struct XBase {
virtual void foo() = 0;
};
struct XBar : public XBase {
virtual void foo() {
cout << "XBar::foo()" << endl;
}
};
// --
// -- my stuff --
struct Base : public XBase {
virtual void foo() {
cout << "Base::foo()" << endl;
}
};
struct Bar : public virtual Base, public virtual XBar { // <-- that's ok, but doesn't let use XBase pointer to Bar instance
virtual void foo() {
cout << "Bar::foo()" << endl;
}
};
// --
int main() {
Bar bar;
bar.foo();
static_cast<Base*>(&bar)->foo();
static_cast<XBar*>(&bar)->foo();
static_cast<XBase*>(&bar)->foo();
return 0;
}
The code isn't compiled because Bar
definition isn't valid.
1) Why compiler isn't able to find out that Base
and XBar
have the same parent and let me use virtual inheritance here?
2) Is it possible to use virtual inheritance if, for example, B
and C
have common ancestor A
, but they have different base classes?
It's like a diamond but there is a another class between C
and A
.
UPD:
Second question the same as -- Why B
and C
have to be deriviatives of A
explicitly?
It would be better to avoid multiple inheritance, and, I guess, it will be a workaround but questions still are.
Upvotes: 1
Views: 132
Reputation: 1334
Modify your code to this:
// -- library stuff --
struct XBase {
virtual void foo() = 0;
};
struct XBar : public XBase {
virtual void foo() {
cout << "XBar::foo()" << endl;
}
};
// --
// -- my stuff --
struct Base : public virtual XBar {
virtual void foo() {
cout << "Base::foo()" << endl;
}
};
struct Bar : public Base {
virtual void foo() {
cout << "Bar::foo()" << endl;
}
};
// --
Upvotes: 1
Reputation: 5083
I think the problem is that XBar
and Base
do not use virtual inheritance from XBase
. If they did I think it would work. But XBar
and Base
as defined each want their own individual XBase
.
Upvotes: 0