11

Would the following code still be negatively affected by the lack of virtual inheritance?

If so, would the negative effects be the same as (or as bad as) the negative effects of multiple inheritance without virtual inheritance if class A did contain data members?

class A
{
public :
    virtual ~A ( ) { }
    virtual int foo ( ) const = 0 ;
} ;

class B : public A
{
public :
    virtual ~B ( ) { }
} ;

class C : public A
{
public :
    virtual ~C ( ) { }
} ;

class D : public B , public C
{
public :
    virtual int foo ( ) const { return 12 ; }
} ;
Giffyguy
  • 20,378
  • 34
  • 97
  • 168
  • 1
    It looks [like you do need the `virtual` see here](http://coliru.stacked-crooked.com/view?id=8bd2970b897e9b44), that is if you expect a pointer to A derived from B to have the same value as if it were derived from C. – Niall Nov 11 '14 at 19:57
  • 1
    By the way, you need to declare a virtual destructor with an empty implementation in A. See http://stackoverflow.com/questions/461203/when-to-use-virtual-destructors – Notinlist Nov 11 '14 at 20:21
  • @Notinlist Thanks for the catch. I added virtual destructors to A, B, and C for safety. – Giffyguy Nov 11 '14 at 20:29

2 Answers2

5

Assuming that you want to use A as a general interface, if you don't make the inheritance virtual you wouldn't be able to do something like this, because there are two inheritance paths to the base class A from the child D:

int main()
{
    D d;
    const A& a = d;

    std::cout << a.foo() << " " << d.foo() << " " << std::endl;
}

If you don't need to use a D as an A then (A) Why do you have it as an abstract base in the first place and (B) No, there is no need for the inheritance to be virtual.

Mark B
  • 95,107
  • 10
  • 109
  • 188
1
class B : public virtual A { } ;
class C : public virtual A { } ;

Using virtual inheritance on the intermediate classes, your class D will only have a single instance of class A, and your code will compile just fine

Niall
  • 30,036
  • 10
  • 99
  • 142
Bart
  • 547
  • 3
  • 16