Is virtual inheritance still necessary when base classes contain no data members?

316 views Asked by At

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 ; }
} ;
2

There are 2 answers

0
Mark B On BEST ANSWER

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.

0
Bart On
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