Evgeny Timoshenko
Evgeny Timoshenko

Reputation: 3257

Why virtual inheritance doesn't work in this case?

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

Answers (2)

Nik
Nik

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

woolstar
woolstar

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

Related Questions