Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ; }
} ;
like image 701
Giffyguy Avatar asked Nov 11 '14 19:11

Giffyguy


2 Answers

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.

like image 161
Mark B Avatar answered Nov 15 '22 19:11

Mark B


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

like image 39
Bart Avatar answered Nov 15 '22 19:11

Bart